Issue
I am trying to use the optional chaining operator (?.) in my express app – it throws error whenever i try.
if (user.address?.postal_code.length > 0 ) {
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/loader.js:1053:16)
I have tried all variations
user?.address?.postal_code?.length
user?.address?.postal_code.length
user?.address.postal_code.length
"engines": {
"node": "10.16.0",
"npm": "6.9.0"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
...
}
Solution
You have 2 options
- Upgrade your Node version. Only these versions support optional chaining. As you can see, only Node 14.5+ supports optional chaining
- If you want to support older versions such as 12, you will need to transpile your code. Take a look at Babel or TypeScript. These programs take your code and transform it into code that is compatible with older Node versions. For example, your code:
if (user.address?.postal_code.length > 0 ) {
// Do stuff
}
Turns into:
var _user$address;
if (((_user$address = user.address) === null || _user$address === void 0 ? void 0 : _user$address.postal_code.length) > 0) {
// Do stuff
}