Javascript의 Nullish coalescing operator (??)의 정의, 사용 예시에 대해 알아봅니다.
- 정의-
MDN에 기재된 Nullish coalescing operator (??)의 정의는 하기와 같습니다.
Nullish coalescing operator (??)
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
같은 falsy라고 모두 (??)를 적용할 수 있는 것은 아닙니다.
(??)를 기준으로 왼쪽데이터가 null이나 undefined일 경우에만 의미가 있습니다.
- 사용 예시-
하기 소스코드를 작성하여 실행합니다.
1
2
3
4
5
6
7
8
9
const data1 =null ?? 'This will be displayed if data1 is null';
const data2 =undefined ?? 'This will be displayed if data2 is undefined';
const data3 =0 ?? 'This will be not displayed even if data3 is falsy';
const data4 =NaN ?? 'This will be not displayed even if data4 is falsy';
Javascript의 Optional chaining (?.)의 정의, 사용 예시에 대해 알아봅니다.
- 정의-
MDN에 기재된 Optional chaining (?.)의 정의는 하기와 같습니다.
Optional chaining (?.)
The optional chaining (?.) operator accesses an object's property or calls a function. If the object is undefined or null, it returns undefined instead of throwing an error.
(?.)연산자의 경우,
객체의 depth가 1단계 일 때에는 사용되지 않고 2단일 때 유용하게 사용 될 것으로 보입니다.
- 사용 예시-
아래와 같이 소스코드를 작성하여 실행합니다.
1
2
3
4
5
6
7
8
9
10
11
12
const music = {
genre: 'R&B',
singer: 'Brian McKnight',
song: { title: 'Home' },
};
console.log(music);
console.log(music.song);
console.log(music.song.title);
console.log(music.lyric?.title); // ?.로 인해 undefined로 출력, app충돌발생하지않음
Javascript의 배열관련 method 중 forEach, map, filter가 있습니다.
각각의 정의와 차이, 예시에 대해 정리합니다.
- 각각의 정의 및 차이-
MDN에 기재된 각 method의 정의는 하기와 같습니다.
Array.prototype.forEach()
The forEach() method executes a provided function once for each array element.
Array.prototype.map()
The map() method createsa new array populated with the results of calling a provided function on every element in the calling array.
Array.prototype.filter()
The filter() method createsa shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
상기내용을 간략히 정의하면 하기와 같습니다.
1. forEach은 각각의 인자를 주어진 함수에 대입 및 실행합니다.
2. map은 각각의 인자를 callback 함수에 대입하고, 결과값들로 이루어진 새로운 배열을 생성합니다.
3. filter는 각각의 인자를 주어진 조건식에 대입 및 확인 하고, true인 경우의 결과값들로 이루어진 새로운 배열을 생성합니다.