cover
JavaScriptInterviewJavascript interviewNullish CoalescingJavaScript operator

What is Nullish Coalescing Operator?

Summary
In JavaScript interview questions, the Nullish Coalescing Operator (??) frequently comes up. It's one of the most useful operators in JavaScript, used to identify null or undefined values.
Category
JavaScript
Interview
Javascript interview
Nullish Coalescing
JavaScript operator
Cover
https://utfs.io/f/82782a17-186a-4ba4-aac4-1f93e89ef0c8-il2et3.jpg
Slug
nullish-coalescing-operator
Date
author
Published
Published

What is the Nullish Coalescing Operator?

ES2020 introduced a new Nullish Coalescing Operator, represented by two question marks (??).
The ?? operator returns the second operand if the first operand is null or undefined. If the first operand is not null or undefined, it returns the first operand.
Still confused? 🙄
Let’s break it down with a simple example. What does ?? do if Ali either went to school or didn't?
// Initially, Ali didn't do anything // meaning the value of 'a' is by default null or undefined. let a = undefined; // or null; let b = "did not go"; let result = a ?? b; // The result is 'b' because Ali didn't go, as the value is undefined. // When does the 'a' variable work? 🤔 // The value of 'a' works when Ali went to school, meaning it's not null or undefined. // We write any value like "went" to the 'a' variable. a = "went"; let result = a ?? b; // The result is 'a' because Ali went.

Syntax

let result = a ?? b;
In this case:
  • If a is null or undefined, the variable result will be assigned the value of b.
  • Otherwise, result will be assigned the value of a.

Example:

let name = null; let defaultName = "Guest"; let displayName = name ?? defaultName; console.log(displayName); // "Guest"
In this example, since the name variable is null, the displayName variable takes the value of defaultName, which is "Guest".

Nullish Coalescing Operator vs. Logical OR (||)

Sometimes, the || (Logical OR) operator can be confused with the ?? operator. However, their working principles are different:
  • The || operator treats values like false, 0, and an empty string "" as false and returns the second operand.
  • The ?? operator only considers null and undefined.

Example:

let count = 0; let result1 = count || 10; console.log(result1); // 10, because 0 is a falsy value. let result2 = count ?? 10; console.log(result2); // 0, because 0 is not null or undefined.
In this example, count is equal to 0. The || operator treats 0 as false and returns 10. However, the ?? operator accepts the value 0 because it is not null or undefined.

Conclusion

The Nullish Coalescing Operator (??) is more convenient when working with default values, specifically when dealing with null or undefined. This operator is particularly useful when you don't want to replace values like false, 0, or an empty string with default values.
 
Back

Similar Articles

Anvarbek Dev © 2024 All rights reserved.