조정밍
JM IT BLOG
조정밍
전체 방문자
오늘
어제
  • 분류 전체보기 (37)
    • Web (8)
      • Server (4)
      • Spring (2)
    • JavaScript (6)
    • Database (1)
    • Java (5)
    • Cryptography (8)
    • Network (1)
    • Reverse (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • JSX
  • 블록암호
  • ln -s
  • Gson
  • 빌드도구
  • nullish
  • react
  • 대칭키암호
  • Gradle
  • 빌터패턴
  • RSA 알고리즘 구현
  • ln 명령어
  • @Builder
  • Base64 #인코딩
  • dll
  • Dynamic Library Link
  • 공개키 암호 알고리즘
  • 정적라이브러리
  • JSONParser
  • RSA 암호화

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
조정밍

JM IT BLOG

[Javascript] Nullish coalescing ("??")
JavaScript

[Javascript] Nullish coalescing ("??")

2021. 8. 4. 22:09

Nullish coalescing operator ??

TypeScript 3.7 부터 지원되는 논리연산자이다.

짧은 문법으로 여러 피연산자 중 그 값이 '확정되어있는' 변수를 찾을 수 있다.

왼쪽 피연산자가 null 이나 undefined 일 때, 오른쪽 피연산자를 return 한다.

 

<예시 코드>

function printText(text) {
  const printText = text ?? 'noText';
  console.log(printText);
}

printText('Hellow World');
printText(null);
printText(undefined);
printText(false);
printText(0);

<실행결과>

 

실행 결과와 같이 null과 undefiend의 경우에만 오른쪽 피연산자로 출력된다.


Nullish coalescing operator ??  /  Logical OR operator ||  차이점

두 연산자는 유사하지만 아래의 차이점이 있다.

- ?? null, undefined 의 경우 오른쪽 코드 실행

- || falsy인 경우 오른쪽 코드 실행

 

<예시 코드>

function printText(text) {
  const printText = text || 'noText';
  console.log(printText);
}

printText('Hellow World');
printText(null);
printText(undefined);
printText(false);
printText(0);

<실행결과>

위 실행 결과와 같이 || 는 null, undefiend 뿐 아니라 false 까지 체크한다.

falsy

falsy에 해당하는 값들

  • false
  • undefiend, null
  • 0, -0
  • "", ''
  •  

leftExpr ?? rightExpr

expression 으로 함수의 결과도 연산 가능하다.

const afterExerc = getInitialState() ?? getProtein();	//proteinSupply

function getInitialState() {
  return null;
}

function getProtein() {
  return 'proteinSupply';
}

No chaiing with And or Or operators

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

?? 연산자는 AND(&&)와 OR(||) 연산자와 직접 같이 사용하는 것은 불가능하다.

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

소괄호와 함께 사용 가능하다.

 

 

 

Reference

- https://im-developer.tistory.com/192 

- https://www.youtube.com/watch?v=BUAhpB3FmS4 

- https://ko.javascript.info/nullish-coalescing-operator

'JavaScript' 카테고리의 다른 글

[javascript] 화살표 함수(Arrow Function)  (0) 2021.09.24
[javascript] 템플릿 리터럴 (Template Literal)  (0) 2021.09.23
[javascript] Optional Chaining '?.'  (0) 2021.09.23
[Javascript] 전개구문(spread syntax)  (0) 2021.09.05
[Javascript] 구조 분해 할당 (Object destructuring)  (0) 2021.08.05
    'JavaScript' 카테고리의 다른 글
    • [javascript] 템플릿 리터럴 (Template Literal)
    • [javascript] Optional Chaining '?.'
    • [Javascript] 전개구문(spread syntax)
    • [Javascript] 구조 분해 할당 (Object destructuring)
    조정밍
    조정밍

    티스토리툴바