Created
August 12, 2021 01:39
-
-
Save sorie/9622fc23f6203d6b7cf5baf1161e5681 to your computer and use it in GitHub Desktop.
javascript tip : 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
const bob = { | |
name: 'Julia', | |
age: 20, | |
}; | |
const anna = { | |
name: 'Julia', | |
age: 20, | |
job: { | |
title: 'Software Engineer' | |
} | |
}; | |
//bad code | |
function displayJobTitle(person) { | |
if(person.job && person.job.title) { | |
console.log(person.job.title); | |
} | |
} | |
//good code | |
function displayJobTitle(person) { | |
if(person.job??.title) { | |
console.log(person.job.title); | |
} | |
} | |
//good code nullish | |
function displayJobTile(person) { | |
const title = person.job?.title ?? 'No Job Yet'; | |
console.log(title); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment