Today I Learned - Rocky Kev

TIL Optional Chaining

POSTED ON:

TAGS:

Very new, very ES2020.

The optional chaining ?. is used to check if a value or a property before ?. is null or undefined .
If it is, it returns undefined . Otherwise, it just returns the value.

You can also use optional chaining with object methods too.

const user = {
name: "Rocky",
hairColor: "black",
};

console.log(user.age); // Can create an Error

console.log("user age?", user?.age); // undefined (no error).

console.log("user hairtype?", user?.hairColor?.hairType); // undefined (no error).

console.log("user name?", user?.name); // Rocky

See the Pen KKWGjNE by rockykev (@rockykev) on CodePen.

Via
https://javascript.plainenglish.io/4-useful-javascript-es2020-features-that-you-should-know-5d690430cf6e


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.