CRA(create-react-app) 프로젝트를 eject하여 소스를 분석하던 도중 신기한 소스를 발견했다.
const something = [
...some
].filter(Boolean);
왜 이렇게 사용할까?
JS에서 제공되는 배열은 아래와 같이 선언하여 사용할 수 있다.
const bad = undefined;
const bomb = [undefined, 5, null, ,,undefined];
const arr = [bad, 1, 2, ...bomb];
// arr = [undefined, 1, 2, undefined, 5, null, undefined, undefined, undefined]
위에서 제공되는 예시와 같이 undefined
또는 null
이 의도하지 않게 들어갈 수 있다.
이러한 가능성은 반복문에서 문제가 발생될 가능성이 크다.
arr.map((item) => {
console.log(item.value); // ERROR! Uncaught TypeError: Cannot read property 'item' of undefined
})
이를 해결하기위해 일반적으로 반복문 내에서 체크하는 로직을 삽입하여 처리하기도 한다.
arr.map((item) => {
if (item) {
return item;
}
console.log(item.value);
})
하지만 이러한 처리방식은 두가지의 문제점을 야기한다.
이보다 더 좋은 방법은 없을까?
그 방법이 filter(Boolean)
을 사용하여 배열을 믿을 수 있는 상태로 만드는 것이다!
심플하고 간단하게 사용할 수 있다.
let array = [false, 0, -0, 0n, "", null, undefined, NaN, {hello: "world"}];
console.log(array.filter(Boolean)); // [{hello: "world"}]
Boolean
을 iterator
로 사용하여 false, 0, -0, 0n, "", null, undefined, NaN
를 제거할 수 있다.
Reference
https://michaeluloth.com/filter-boolean