As we know, when an ECMAScript proposal reaches stage 4, it is ready to be included in the ECMAScript standard and browsers can start implementing it in their JavaScript engines. The following table shows the stages a proposal has to go through until it is finally landed in the hands of the public.
(source: gist.github.com)
In 2019, I published the article “What’s new in JavaScript: Google I/O 2019 Summary” about the new JavaScript featured landed in 2019. Not sure if I can call it “popular” but it gained some good traction among JavaScript developers and I thought, why not do the same for the year 2020.
Though Google I/O 2020 has been canceled, it doesn’t stop the ECMAScript (JavaScript standard) development process. This year, we are expected to see some cool new JavaScript features coming to browsers and Node. Some of these features are pretty new and might not be available in your browser, so use Firefox 80 or Chrome 85 to test them out or use Babel plugins.
We have abused &&
operator to get around a few sneaky things. As we know, JavaScript objects can be nested, and accessing the nested property isn’t always runtime safe operation. Let me show you how.
(source: gist.github.com)
In the above example, the object obj
is a plain JavaScript object but it is deeply nested. So accessing the value of the property p
would need the traversal of it obj > a > b > c > p
. Let’s what happens if any path is missing.
▶ obj.a.b.c.p
◁ 1
▶ obj.a.b.d.p
◁ undefined
▶ obj.a.b.e.p
◁ Uncaught TypeError: obj.a.b.e is null
▶ obj.a.b.f.p
◁ Uncaught TypeError: obj.a.b.f is undefined
So in the first case, accessing obj.a.b.c.p
returned 1
because it’s a valid path. Accessing property p
on obj.a.b.d
was also a success since obj.a.b.d
is a number
which also kind-of an object as we can access properties on it.
However, we can’t access properties on null
and undefined
since they are not objects. These together are called the nullish value. Whenever you try to access properties on a nullish value, JavaScript will throw a TypeError
.
So how can we circumnavigate this? Well, we could use if/else
statement to check if a property is non-nullish and travel deep.
if(obj.a){
if(obj.a.b){
if(obj.a.b.f){
console.log( obj.a.b.f.p );
}
}
}
In the above snippet, we are checking if every ancestor of the property p
is not nullish. Since obj.a.b.f
would return undefined
, the inner console.log
statement would not be evaluated, therefore no TypeError
.
#es6 #javascrit #web-development #node #ecmascript