How to avoid "Cannot read property 'name' of undefined" in JavaScript
#7 · 2017-01-17 (updated 2020-01-04) · JavaScript, TypeScriptJavaScript objects may have properties.
If you are trying to access a property that does not exists, you will just get undefined
back.
And if you try to get a property of an undefined
value, you will get an error message.
var obj = {};
obj.hello; // Evaluates to `undefined`
obj.hello.world; // Uncaught TypeError: Cannot read property 'world' of undefined
ES2020 introduced a new feature called optional chaining to avoid that.
You can use it by replacing .
with ?.
as in obj.hello?.world
.
The optional chaining operator ensures that this expression does not throw an exception but just returns undefined
.
Note that TypeScript introduced support for optional chaining in version 3.7.
More information about optional chaining can be found in the following links.