What is Nullish coalescing operator "??" and how to use it effectively in JavaScript?

← PrevNext →

Nullish coalescing operator ?? is a logical operator that returns right-hand side value (operand) if left-hand side value (operand) is "null" or "undefined". Let's understand this operator with two simple examples.

1) Example One

<script>
  const name = 'arun banik';
  let age;
  let v = age ?? name;          // using null coalescing operator (??).
  document.write (v);           // Output: arun banik, because age is undefined.
</script>
Try it

The expected output is the name. The "nullish coalescing operator" returned the name, right-hand value (or operand) because variable "age" is undefined.

I have declared variable "age". However, I have not assigned any value to it. So its undefined.

➡️ Remember: If both, right-hand and left-hand operands have no value, then it returns "undefined".

2) Example Two

Here's another scenario. I have defined and assigned values to each variable.

<script>
  const name = 'arun';
  let age = 30;
  let v = age ?? name;
  document.write (v);       // Output: 30.
</script>
Try it

The output is the age. The ?? operator returned the left-hand value (operand), since variable age (left-hand operand) has a value assigned.

➡️ Remember: "" or '' (blank or emplty quotes) are not Null or Undefined. So the below example will return blank.

<script>
  const name = 'arun';
  let age = '';
  let v = age ?? name;
  document.write (v);		// Output: blank.
</script>

Also try this example.

Here I am using "||" (OR operator) to return a default value, if age is "undefined".

<script>
  const name = 'arun banik';
  let age;
  let v = (age || 30) ?? name;	// If age is undefined, return a default value.
  document.write (v);		// Output: 30
</script>

← PreviousNext →