Last active
February 4, 2020 04:48
-
-
Save HaiBV/4d16c3b928dbbd01bf16e6bf6257879c to your computer and use it in GitHub Desktop.
Optional Chaining
This file contains 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
// without Optional Chaining | |
function sayHi(user) { | |
let name = (user && user.name && user.name.toUpperCase()) || "Unknown"; | |
console.log(`Hi Mr. ${name}`); | |
} | |
sayHi({}); // Hi Mr. Unknown | |
sayHi(); // Hi Mr. Unknown | |
// with Optional Chaining | |
function sayHi(user) { | |
let name = ( user?.name?.toUpperCase?.() ) || "unKnown"; | |
console.log(`Hi Mr. ${name}`); | |
} | |
// (property == undefined || property == null) ? undefined : property | |
// Optional Chaining systax | |
// obj?.prop | |
// obj?.[expr] | |
// arr?.[index] | |
// func?.(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Optional chaining MDN