20241029 자바스크립트 모듈, forEach & filter 메서드

모듈이란?

개발하는 애플리케이션의 크기가 커지면 파일을 여러개로 분리해야 하는데, 이때 분리된 파일 각각을 모듈이라고 한다.
모듈화를 하면 더 코드가 깔끔해지고 다른 프로그램에서도 이전에 모듈화해 놓은 것과 동일한 기능을 재사용하기도 쉬워진다고 한다.

모듈에 import, export를 적용해 다른 모듈을 불러와 함수를 호출하는 식으로 사용한다.

export & import 하는 법

export에는 default exportnamed export가 있다.

default

default export는 한 모듈당 한번만 사용할 수 있다.

default 키워드는 해당 기능을 기본으로 내보내고 싶을 때 사용한다.
Airbnb 자바스크립트 스타일 가이드에 따르면 single export인 모듈이면 default export를 쓸 것을 권장하고 있다.

// bad
export function foo() {}

// good
export default function foo() {}


default로 내보낸 함수를 가져올 때는 다음과 같이 중괄호 없이 함수의 이름으로 가져오면 된다.

import foo from './foo.js'


named

named export는 한 모듈에서 여러번 사용할 수 있다.

여러 기능을 내보낼 때는 중괄호를 사용해서 내보낸다.

export { myFunction1, myFunction2 };


named로 내보낸 함수를 가져올 때도 중괄호 안에 함수의 이름을 넣어 가져온다.

import { myFunction1, myFunction2 } from './myModule.js'



네이밍 컨벤션

Airbnb 자바스크립트 스타일 가이드에 따르면 base filename은 default export의 이름과 일치해야한다고 한다.

// file 1 contents
class CheckBox {
  // ...
}
export default CheckBox;

// file 2 contents
export default function fortyTwo() { return 42; }

// file 3 contents
export default function insideDirectory() {}

// in some other file
// bad
import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename
import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export
import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export

// bad
import CheckBox from './check_box'; // PascalCase import/export, snake_case filename
import forty_two from './forty_two'; // snake_case import/filename, camelCase export
import inside_directory from './inside_directory'; // snake_case import, camelCase export
import index from './inside_directory/index'; // requiring the index file explicitly
import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly

// good
import CheckBox from './CheckBox'; // PascalCase export/import/filename
import fortyTwo from './fortyTwo'; // camelCase export/import/filename
import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"
// ^ supports both insideDirectory.js and insideDirectory/index.js


또한, function을 export할 때는 camelCase를,

function makeStyleGuide() {
  // ...
}

export default makeStyleGuide;

constructor / class / singleton / function library / bare object를 export할 때는 PascalCase를 사용하라고 한다.

const AirbnbStyleGuide = {
  es6: {
  },
};

export default AirbnbStyleGuide;


약어 및 이니셜은 모두 UPPERCASE로 작성하거나 모두 lowercase로 작성해야 한다.

// bad
import SmsContainer from './containers/SmsContainer';

// bad
const HttpRequests = [
  // ...
];

// good
import SMSContainer from './containers/SMSContainer';

// good
const HTTPRequests = [
  // ...
];

// also good
const httpRequests = [
  // ...
];

// best
import TextMessageContainer from './containers/TextMessageContainer';

// best
const requests = [
  // ...
];




forEach 메서드

각 배열 원소에 동일하게 함수를 적용하고 싶을 때는 forEach() 메서드를 사용하면 된다.

const numbers = [1, 5, 2, 17, 18];

numbers.forEach(function(number) {
  console.log(number);
});

//// 출력
// 1
// 5
// 2
// 17
// 18


forEach() 메서드는 요소, 인덱스, 호출한 배열을 파라미터로 받는다.
또한 map 메서드처럼 return 값을 모아서 처리하는 것이 아니라 그냥 바로 함수를 호출하는 것이다.

따라서 다음과 같이 newNumbers를 호출해보면 undefined가 출력된다.

const numbers = [1, 5];

const newNumbers = numbers.forEach((currentElement, index, array) => {
    console.log(`요소: ${currentElement}, index: ${index}`);
    console.log(array);
});

console.log(newNumbers);

//// 출력
// 요소: 1, index: 0,
// [1, 5]
// 요소: 5, index: 1
// [1, 5]
// undefined


다음과 같이 배열의 값 변경도 가능하다.

const numbers = [1, 5, 2, 17, 18];

numbers.forEach(function(number, i) {
  numbers[i] = number + 3;
});

console.log(numbers);

//// 출력
// [4, 8, 5, 20, 21]



filter 메서드

배열 원소의 값을 일부 걸러내 그 결과로 새로운 배열을 만들고자 할 때는 filter() 메서드를 사용하면 된다.

function isBigEnough(value) {
  return value >= 10;
}

const myArr = [12, 5, 8, 130, 44]

const filtered = myArr.filter(isBigEnough);

console.log(myArr);
console.log(filtered);

//// 출력
// [12, 5, 8, 130, 44]
// [12, 130, 44]

filter 메서드에 인수로 전달된 함수는 배열 원소 확인 값에 따라 true 또는 false를 반환하고,
반환되는 값은 배열 원소가 새로운 배열에 추가될 것인지를 결정한다.
즉, 함수에서 true를 반환하면 새 배열에 추가되고, 그렇지 않으면 추가되지 않는다.

파라미터로는 forEach() 메서드와 똑같이 요소, 인덱스, 호출한 배열를 받는다.
모든 파라미터를 사용하고 싶으면 arrow function을 활용하면 된다.

let words = ["spray", "limit", "exuberant", "destruction", "elite", "present"];

const modifiedWords = words.filter((word, index, arr) => {
  arr[index + 1] += " extra";
  return word.length < 6;
});

console.log(words);
console.log(modifiedWords);

//// 출력
// ['spray', 'limit extra', 'exuberant extra', 'destruction extra', 'elite extra', 'present extra', 'undefined extra']
// ['spray']

Categories:

Updated:

Leave a comment