Have you ever been watching a tutorial and been amazed when a developer uses some really cool feature of JavaScript you’ve never seen before? In this blog, we will share five JavaScript features that are not widely known but can drastically change the way you write code.
1: Nullish Coalescing
Nullish coalescing in JavaScript is a way to handle situations where you want to choose a value from a list of options but want to avoid picking a value that’s empty or null.
Imagine you have a bunch of variables, and you want to select the first one that actually has a meaningful value. You can use the nullish coalescing operator (??
) to do this.
Here are some code examples to illustrate:
- With Nullish Coalescing (??)
let option1 = "Chocolate Ice Cream";
let option2 = null;
let option3 = "Vanilla Ice Cream";
let favoriteOption = option1 ?? "No favorite option found";
console.log(favoriteOption); // Output: "Chocolate Ice Cream"
In this example, we’re choosing our favorite ice cream flavor among option1
, option2
, and option3
. Nullish coalescing helps us pick the first non-empty, non-null value, which is option1
in this case.
- Without Nullish Coalescing