Skip to content

Instantly share code, notes, and snippets.

@HaiBV
Last active February 4, 2020 04:48
Show Gist options
  • Save HaiBV/4d16c3b928dbbd01bf16e6bf6257879c to your computer and use it in GitHub Desktop.
Save HaiBV/4d16c3b928dbbd01bf16e6bf6257879c to your computer and use it in GitHub Desktop.
Optional Chaining
// 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)
@HaiBV
Copy link
Author

HaiBV commented Feb 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment