Last active
August 12, 2021 00:51
-
-
Save sorie/c065adb38631c60bc5adfcf468a2ef71 to your computer and use it in GitHub Desktop.
javascript : nullish-coalescing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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