Understanding the Difference Between || (OR) and ?? (nullish coalescing) Operators in JavaScript

Understanding the Difference Between || (OR) and ?? (nullish coalescing) Operators in JavaScript

Both || (OR operator) ?? (nullish coalescing operator) are the way of assigning default value in Javascript when dealing with undefined or other falsy values. However, they behave different in certain situations.

The main difference between the two operators is how they handle falsy values for example consider following code.

const value = false;
console.log(value || 500); // Output: 500
console.log(value ?? 500); // Output: false

In this scenario, the output is different in each operator.

But Why ?

The reason is ?? operator return default value only if left side value is null or undefined while || operator consider following scenarios,

  1. false: The boolean false value.

  2. 0: The number zero (integer).

  3. -0: The negative zero (integer).

  4. 0n: The BigInt zero.

  5. NaN: Not-a-Number, a special value that represents the result of an undefined or unrepresentable mathematical operation.

  6. null: A null value, representing the absence of any value or object.

  7. undefined: A value that is automatically assigned to variables that have just been declared or to object properties that do not exist.

  8. "": An empty string.

Here is an example code

console.log(false || 'default'); // Output: 'default'
console.log(0 || 42);            // Output: 42
console.log(NaN || 100);         // Output: 100
console.log(null || 'Hello');    // Output: 'Hello'
console.log(undefined || 123);   // Output: 123
console.log('' || 'Fallback');   // Output: 'Fallback'

Now let’s compare this code with ?? operator

console.log(false ?? 'default'); // Output: false
console.log(0 ?? 42);            // Output: 0
console.log(NaN ?? 100);         // Output: NaN
console.log(null ?? 'Hello');    // Output: 'Hello'
console.log(undefined ?? 123);   // Output: 123
console.log('' ?? 'Fallback');   // Output: ''

As you see the ?? operator only return it’s right-side value if left-side value is null or undefined.

In conclusion, understanding the differences between the **||**and ?? operators in JavaScript is essential for assigning default values correctly, depending on whether you want to consider all falsy values or only **null**and undefined .