Skip to content

Instantly share code, notes, and snippets.

@sorie
Last active August 12, 2021 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorie/c065adb38631c60bc5adfcf468a2ef71 to your computer and use it in GitHub Desktop.
Save sorie/c065adb38631c60bc5adfcf468a2ef71 to your computer and use it in GitHub Desktop.
javascript : nullish-coalescing
//nullidh coalescing operator ?? is only case null, undefined check.'
//do not confusing to Logical OR operator || is only case false(0, undefined, null, "",'',``) or true check.
//bad code
function printMessage(test){
let message = text;
if(text == null || text == undefined) {
message = 'Nothing to display';
}
console.log(message);
}
//good code
function printMessage(text){
const message = text ?? 'Nothing to display';
console.log(message)
}
//default parameter is only for undefined
function printMessage(text = 'Nothing to display') {
console.log(text);
}
//Logical OR operator
function printMessage(text){
const message = text || 'Nothing to display';
console.log(message)
}
printMessage('hello');
printMessage(undefined);
printMessage(null);
printMessage(0);
printMessage("");
//another case using nullidh coalescing
const result = getInitialState() ?? fetchFromServer();
console.log(result);
function getIni9tialState() {
return null;
}
function fetchFromServer() {
return 'Hiya from german';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment