Skip to content

Instantly share code, notes, and snippets.

@smpnjn
Created December 5, 2020 12:23
Show Gist options
  • Save smpnjn/c271e31d0ef75b7410a03085ceeed78c to your computer and use it in GitHub Desktop.
Save smpnjn/c271e31d0ef75b7410a03085ceeed78c to your computer and use it in GitHub Desktop.
/*
Don't limit yourself, all of these work:
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
*/
let defineUser = {
name: "Markus",
age: 29,
location: {
country: "USA"
}
}
// We can now remove the layers of undefined checking we had before
if(typeof defineUser.location?.address !== "undefined") {
console.log(defineUser.location.address);
}
else {
console.log("No address is defined");
// If the function doesn't exist, nothing will happen
generateAddress?.();
}
// You can check for elements like this as well
console.log(defineUser?.["salary"]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment