티스토리 뷰

반응형

nodejs를 통해 백엔드를 만들거나 react로 프런트를 만들 때, null 이나 undefined를 피하기 위한 분기를 조금더 똑똑하게 해보자. 

 

 

1. Nullish coalescing operator (??)

우선은 병합 연산자에 대해 알아보자. 병합 연산자는 왼쪽 피연산자기 null이거나 undefined의 경우는, 오른쪽 피연산자를 반환하고, 그렇지 않은 경우는 왼쪽을 반환한다. 아래의 예를 보자.

 

const foo = null ?? 'default string';
console.log(foo);
// "default string"

const aoo = undefined ?? 'default string';
console.log(aoo);
// "default string"

const boo = false ?? 'default string';
console.log(boo);
// false

const coo = '' ?? 'default string';
console.log(coo);
// ""


const doo = 0 ?? 42;
console.log(doo);
// Expected output: 0

 

위의 예시에서 주의 할 점은 OR 연산자와 다르게 boolean이나 0과 같은 기본 if문의 false 값에 상관없이, null과 undefined의 경우만 반응한다는 점이다.

 

2. OR 연산자(Logical OR)

위의 내용과 바로 비교를 해보자.

const foo = null || 'default string';
console.log(foo);
// "default string"

const aoo = undefined || 'default string';
console.log(aoo);
// "default string"

const boo = false || 'default string';
console.log(boo);
// "default string"

const coo = '' || 'default string';
console.log(coo);
// "default string"


const doo = 0 ?? 'default string';
console.log(doo);
// "default string"

 

위의 부분에서 확인 할 부분은 '' 부분도 오른쪽 피연산자를 반환한다는 것이다. 나머지 부부은 위 예제를 확인하면 이해가 가능 할 것이다. 기본적으로 or 연산자는 왼쪽에서 오른쪽으로 연산을 진행한다. 아래의 예를 보자. 

 

function A() {
  console.log('called A');
  return false;
}

function B() {
  console.log('called B');
  return true;
}

console.log(B() || A());
// called B
// true

console.log(A() || B());
// called A
// called B
// true

 

왼쪽 피연산자의 return값이 true이면 오른쪽 피연산자의 로직을 수행하지 않는 것을 확인 할 수 있다. 정리하면 아래의 값은 false로 리턴한다.

  • null;
  • NaN;
  • 0;
  • empty string ("" or '' or ``);
  • undefined

 

 

3. && 연산자와 || 연산자의 우선순위

우선순위는 &&가 먼저 우선순위로 발생한다.

 

true || false && false      // returns true
(true || false) && false    // returns false

 

() 괄호가 포함 된다면 먼저 연산하지만, 그렇지 않은 경우는 ||가 먼저 연산한다.

 

 

4. coalescing operator example(??)

병합연산자를 ??=를 조금더 활용하는 방법을 알아보자.

 

function config(options) {
  options.duration ??= 100;
  options.speed ??= 25;
  return options;
}

config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }

 

??= 의 경우에 값이 null 이나 undefined의 경우에만 값이 대입하고, 그렇지 않는 경우는 무시하고 넘어간다. config({ duration: 125 }); 의 경우는 duration의 값이 있기 때문에 100이 포함되지 않았지만, speed의 경우는 값이 포함되어 있지 않기 때문에 25가 대입되어 return 되는 것을 확인 할 수 있다.

 

 

5. 추가

AND(&&), OR(||)과 ??를 같이 사용하는 것은 불가능 하다.

 

null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError

 

아래와 같이 괄호를 사용하여 우선순위를 지정하는 것은 가능하다.

 

(null || undefined) ?? "foo"; // returns "foo"

 

 

 

 

 

참고 : https://developer.mozilla.org/en-US/

 

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함