const car1 = { | |
brand: ‘carBrand1’ | |
color: ‘red’ | |
}; | |
const car2 = undefined; | |
// it logs a value | |
console.log(car1.color); | |
/* | |
if we do not use null safety mechanism next part of the code will throw Uncaught | |
ReferenceError: car2 is not defined | |
*/ | |
console.log(car2.color); | |
/* | |
if we use null safety mechanism ?. we will avoid throwing an error and program | |
will continue to work - it logs undefined | |
*/ | |
console.log(car2?.color) | |
/* | |
like in all other programming languages which does not have null safety mechanism, | |
we can also write last part of the code in the different, more complicated, way | |
and add possibility to forget some of the cases which then can cause ReferenceError | |
*/ | |
console.log(car2 !== undefined ?? car2 !== null ? car2.color : undefined) |