Vedansh Mehra
Vedansh Mehra

Reputation: 33

I am trying to use optional chaining in JS and it showing error

Why is my JS snippet throwing an error on console.log?

var person = {
    name: 'John',
    pet: {
        name: 'Trixi',
    }
};

var petName = person.pet?.name;
console.log(petName);

Uncaught SyntaxError: Unexpected token '.'

Upvotes: 3

Views: 1921

Answers (1)

novalagung
novalagung

Reputation: 11502

The Optional chaining operator is currently supported on Chrome v80 or more, Firefox v74, and other browser's newest versions. More details: https://caniuse.com/mdn-javascript_operators_optional_chaining

However, you can still enable it on the older browser by enabling the Experimental JavaScript config on the browser.

For example in Chrome, to do that, do access chrome://flags/#enable-javascript-harmony in the URL, and then enable.

Upvotes: 2

Related Questions