Search code examples
javascriptnode.jssyntaxoptional-chaining

Why is optional chaining not working in my Node REPL?


I literally copy pasted example code from MDN but optional chaining wont work in my node(v12.13.0) REPL. Throws out a syntax error saying that the dot after the question mark is invalid. What's going on ? I have already used this expression in a React App and it seems to be working fine.

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};


const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined


Solution

  • It's only coming for Node 14 under --harmony: How to use optional chaining in Node.js 12

    You can use babel optional chaining plugin if you want this feature in node: https://babeljs.io/docs/en/next/babel-plugin-syntax-optional-chaining.html