Photo by Sincerely Media on Unsplash
JavaScript 2020 - New Features - Part 1
ECMAScript 2020(ES11) : New Capabilities
Optional Chaining Operator
It is used for enhancing safety of the program when accessing an object. When an object's non-existent property is accessed the program returns undefined or might crash depending on the scenario. To solve the above the optional chaining operator can be used. The symbol ?. represents optional chaining operator.
Syntax: object?.property
// optional chaining - ?. - enhances safety
let obj = {
name: {
firstname : "ram",
lastname : "kumar"
}
}
//console.log(obj.name.middlename.name); // crashes
console.log(obj.name.middlename?.name); // undefined
// with null
let arr =null;
//console.log(arr[1]); // crash
console.log(arr?.[1]); // undefined
let fx = () => console.log("fx");
fx = null;
//fx(); // crash
fx?.();
In the above code the optional chaining operator(?.) is used to avoid crash when accessing the object.
Nullish Coalescing Operator
If a given object is null or undefined nullish coalescing operator can be used to provide a default value. The symbol ?? is used for representing Nullish coalescing operator.
let obj = {
name: {
firstname : "ram",
lastname : "kumar"
}
}
// Nullish Coalescing operator - ??
// if a value is null or undefined - can give default value
console.log(obj.name.middlename ?? "default name");
let num = null
num = num ?? 5
console.log(num) // 5
BigInt
Now programmer can handle large integer numbers beyond the size of Number.MAX_SAFE_INTEGER. The value has to be suffixed using n or can be created using BigInt() function.
// big int
const big = 1234124123412412341234123412341234n;
let big2 = BigInt(45252345235252352353523534523453252345235235345);
console.log("value", big, big2);
console.log("typeof", typeof big, typeof big2);
Complete Code Listing
// optional chaining - ?. - enhances safety
let obj = {
name: {
firstname : "ram",
lastname : "kumar"
}
}
//console.log(obj.name.middlename.name); // crashes
console.log(obj.name.middlename?.name); // undefined
// with null
let arr =null;
//console.log(arr[1]); // crash
console.log(arr?.[1]); // undefined
let fx = () => console.log("fx");
fx = null;
//fx(); // crash
fx?.();
obj = {
name: {
firstname : "ram",
lastname : "kumar"
}
}
// Nullish Coalescing operator - ??
// if a value is null or undefined - can give default value
console.log(obj.name.middlename ?? "default name");
let num = null
num = num ?? 5
console.log(num) // 5
// big int
const big = 1234124123412412341234123412341234n;
let big2 = BigInt(45252345235252352353523534523453252345235235345);
console.log("value", big, big2);
console.log("typeof", typeof big, typeof big2);