FrontendDeveloper.in

ECMAScript question detail

Nullish Coalescing Operator

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This operator replaces || operator to provide default values if you treat empty value or '', 0 and NaN as valid values. This is because the logical OR(||) operator treats(empty value or '', 0 and NaN) as falsy values and returns the right operand value which is wrong in this case. Hence, this operator truly checks for nullish values instead falsy values.

let vehicle = {
car: {
name: "",
speed: 0
}
};

console.log(vehicle.car.name || "Unknown"); // Unknown
console.log(vehicle.car.speed || 90); // 90

console.log(vehicle.car.name ?? "Unknown"); // ""(empty is valid case for name)
console.log(vehicle.car.speed ?? 90); // 0(zero is valid case for speed)

In a short note, nullish operator returns a non-nullish value and || operator returns truthy values.

Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399