Nullish coalescing operator (??)

단단한어린이·2022년 7월 29일
0

Javascript

목록 보기
16/17
post-thumbnail
post-custom-banner

Bad code

function printMessage(text){
  let message = text;
  if (text == null || text == undefined){
    message = 'Nothing to print';
  }
  console.log(message);
}

Good code

function printMessage(text){
  const message = text ?? 'Nothing to print';
  console.log(message);

printMessage('Hello');
printMessage('undefined');
printMessage('null');
Hello
Nothing to print
Nothing to print

Default parameter is only for undefined.

function printMessage(text = 'Nothing to print'){
  console.log(text);
  
printMessage('Hello');
printMessage('undefined');
printMessage('null');
Hello
Nothing to print
null

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.

This can be seen as a special case of the logical OR (||) operator, which returns the right-hand side operand if the left operand is any falsy value, not only null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors.
Sources : MDN

profile
Footprints in Coding
post-custom-banner

0개의 댓글