Created
December 1, 2024 17:12
-
-
Save TGITS/dbcd057293eb9e5d5fb26d910c2414cc to your computer and use it in GitHub Desktop.
Exemple d'utilisation de l'opérateur de chaînage optionnel
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
let pokemon = { | |
name: "Bulbasaur", | |
type: [ | |
"Grass", | |
"Poison" | |
], | |
base: { | |
hp: 45, | |
attack: 49, | |
defense: 49, | |
specialAttack: 65, | |
specialDefense: 65, | |
speed: 45 | |
} | |
}; | |
//Plutôt que d'écrire ... | |
if (pokemon && pokemon.name && pokemon.base && pokemon.base.specialDefense) { | |
console.log(`The pokemon name is ${pokemon.name} and its special defense amount to ${pokemon.base.specialDefense}`); | |
} | |
//... on peut écrire | |
if (pokemon?.name && pokemon?.base?.specialDefense) { | |
console.log(`The pokemon name is ${pokemon.name} and its special defense amount to ${pokemon.base.specialDefense}`); | |
} | |
pokemon.base = null; | |
if (pokemon?.name && pokemon?.base?.specialDefense) { | |
console.log(`The pokemon name is ${pokemon.name} and its special defense amount to ${pokemon.base.specialDefense}`); | |
} else { | |
console.log("Cannot display anything, something is null or undefined"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment