JavaScript Optional chaining

less than 1 minute read

You should get Uncaught TypeError: Cannot read property ~~ of undefined, because you accessed txt property even though there is not middleName property.

function user (firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
}
const me = new user2('ys', 'a')
console.log(me.middleName.txt) // Uncaught TypeError: Cannot read property 'txt' of undefined at <anonymous>

Instead of using ., use ?.

function user (firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
}
const me = new user2('ys', 'a')
console.log(me.middleName?.txt) // undefined

You got just undefined.

?. operator does not cause Cannot read property undefined error, even when there is not middleName property.

You can use ?. operator on function call and [].

Reference: MDN

Tags:

Categories:

Updated:

Leave a comment