Null-safe property access (and conditional assignment) in ES6/2015
Update (2022-01-13): Seems people are still finding this, here's the current story:
- Optional Chaining is in the specification now (ES2020) and supported by all modern browsers, more in the archived proposal: https://github.com/tc39/proposal-optional-chaining
- babel-preset-env: If you need to support older environments that don't have it, this is probably what you want https://babeljs.io/docs/en/babel-preset-env
- Babel v7 Plugin: https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
Update (2017-08-01): If you want to use an official plugin, you can try the alpha build of Babel 7 with the new transform. Your mileage may vary
https://www.npmjs.com/package/babel-plugin-transform-optional-chaining
Original:
A feature that accomplishes that is currently in stage 1: Optional Chaining.
https://github.com/tc39/proposal-optional-chaining
If you want to use it today, there is a Babel plugin that accomplishes that.
https://github.com/davidyaha/ecmascript-optionals-proposal
Safe way to check the deep of object's property?
That is exactly why you have Optional chaining (introduced in ES2020) in javascript.
It's an operator (?.) which enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is null/undefined so it actually protects you from getting a null reference error.
console.log(object.level1?.level2?.level3);
What does ?. and ?? operator in javascript do?
The ?.
is called the optional chaining operator (TC39 Stage 4), it is used when you are not sure whether a nested property exists or not. If you try to use the .
operator to access a property which is undefined
you get a TypeError
.
For example:
const obj = {foo: {} };
//This is safe, results in undefined
console.log(obj?.foo?.bar?.baz);
//This results in Uncaught TypeError: Cannot read property 'baz' of undefined
console.log(obj.foo.bar.baz);
Where as the ??
is called the null coalescing operator (TC39 Stage 3). When you are using falsy values like an empty string ""
or a 0
with a ||
operator the operand on the right hand side of the ||
is returned as the falsy value is ignored.
The ??
comes handy when you don't want that and actually you want to consider the falsy values. If the value on the left is a null
or undefined
only then the value on the right of the ??
is taken:
For example:
const empString = "";
const defaultValue = empString || "A default value";
//Outputs A default value as "" empty string is falsy
console.log(defaultValue);
const actualValue = empString ?? "A default value";
//Does not print the default value as the empString is neither null or undefined
console.log(actualValue);
Same for other falsy values like 0
, false
, in disagreement with the ||
operator which will output the 'default
string:
console.log(false ?? 'default') //false
console.log(0 ?? 'default') // 0
Only for undefined
and null
this will output the default value provided in agreement with the ||
operator:
console.log(undefined ?? 'default') //default
console.log(null ?? 'default') //default
What are the possible way to handle TypeError Cannot read property 'something' of null?
You have two options:
1- Always check for being null
:
let blah;
if (obj) {
blah = obj.something;
}
2- Use Optional Chaining
const blah = obj?.something;
From the docs:
The ?. operator functions similarly to the . chaining operator, except
that instead of causing an error if a reference is nullish (null or
undefined), the expression short-circuits with a return value of
undefined.
What is the ?. operator and Where I can the use ?? Nullish Coalescing Operator in JavaScript
It's a bit unclear what you're asking. This code:
const location = {
lat: data?.coords?.latitude,
long: data?.coords?.longitude
}
assigns undefined
to lat
if either data
or data.coords
is null
or undefined
(rather than throwing an error). But if data
and data.coords
are both not null
or undefined
, it assigns data.coords.latitude
and data.coords.longitude
to lat
and long
. It's the new optional chaining operator.
The next line also uses it, but:
If the
uid
could be a falsy value (like""
or0
), you should use the new nullish coalescing operator as well:??
rather than||
.If
auth
may benull
orundefined
, you need another?.
So:
const docId = auth?.currentUser?.uid ?? '123'
What does ?. and ?? mean in javascript
1. Optional chaining (?.)
From MDN said that
The optional chaining operator (?.) permits reading the value of a
property located deep within a chain of connected objects without
having to expressly validate that each reference in the chain is
valid.
The ?. operator functions similarly to the . chaining operator, except
that instead of causing an error if a reference is nullish (null or
undefined), the expression short-circuits with a return value of
undefined. When used with function calls, it returns undefined if the
given function does not exist.
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
console.log(adventurer.dog?.name); // expected output: undefined
console.log(adventurer.dog.name); // Thow an error message like
//`"message": "Uncaught TypeError: Cannot read property 'name' of undefined",`
Related Topics
How to Connect to SQL Server Database from JavaScript in the Browser
How to Avoid 'Cannot Read Property of Undefined' Errors
Why Are Global Variables Considered Bad Practice
How to Handle Newlines in Json
Add Inline Style Using JavaScript
Changing Background Based on Time of Day (Using JavaScript)
How to Compare Two Color Values in Jquery/Javascript
Can't Change Border Color of Material-Ui Outlinedinput
Correct JavaScript Inheritance
How to Count String Occurrence in String
Ecmascript Template Literals Like 'Some ${String}' Are Not Working
How to Update the Parent'S State in React
Converting JavaScript Object With Numeric Keys into Array