Cyberithub

How does JavaScript double question mark (??) operator works

Advertisements

In this tutorial, we will see how does JavaScript double question mark (??), also known as null coalescing operator works. JavaScript is a web programming language developed to make web pages interactive. It was developed by James Clark and Brendan Eich in 1995. It is a scripting language based on C/C++ and Java. The nullish coalescing operator(??) was introduced in ES11 as an alternative to the long-used logical OR (||). It was actually added with lot of extra capabilities and features that has surely replaced lot of applications of OR(||) operator. We will see all the capabilities and features provided by nullish coalescing operator(??) in detail with the help of great examples.

 

Prerequisites

In order to follow through this article:-

  • You need to have a basic understanding of JavaScript.
  • You need a code editor like visual studio, atom or sublime text. Alternatively, you can download an Integrated Development Environment (IDE). An IDE is an improved code editor with added qualities customized to help you write and execute codes easier. Visual studio code is the most popular IDE used for developing web programs.

How does JavaScript double question mark (??) operator works

How does JavaScript double question mark (??) operator works

Also Read: Step By Step to Install Selenium WebDriver for JavaScript

JavaScript has some neat features, such as the nullish coalescing operators, aka the double question mark (??). These allow us to write code that looks cleaner and easier to read.in this article, we will walk you through how the double question mark works, and all examples will be compiled using  Microsoft visual studio code environment. The nullish coalescing (??) operator allows us to assign a default value to variables that don't have a value assigned to them.

Nullish coalescing(??) operator returns its left operand if it has a value; otherwise, it returns its right operand. For example, let’s check whether a variable named x exists or not. If it does exist, then return its value. Otherwise, return undefined. Furthermore, we want to assign the outcome of our expression to either x or y depending on whether x exists or not. This is where the double question mark operator (??) Comes into play.

The outcome of this expression x ?? y is:-

  • if x is defined with a value, then x,
  • if x is not defined with a value, then y.

Furthermore, we can conclude that the double question mark operator ?? will always return  the first argument as long its value is neither null or undefined. else, the second value.

 

Why to use Double Question Mark (??) 

Have you ever wondered why some developers prefer using double question mark (??) or the nullish coalesce operator (??). There are four main reasons why developers use these operators:-

  • It is used for Assigning a default value to a variable.
  • It is used to check if a value exist.
  • It is useful when you don't want to check all falsy values.
  • It is useful when you want to replace values in an array.

Let’s take a look at each case - the nullish coalescing operator (??) is used to assign a default value to a JavaScript variable. This operator ?? returns the left hand side expression if it evaluates to true or else return the right hand side expression.

The double question mark operator is very useful because it allows us to assign a default value for variables without explicitly writing them. For example, if we want to assign a default value to a visitor who did not state his or her name. The below statement would assign “Anonymous” to a visitor without name, i.e whose name return as null or undefined. For example:-

let visitor;
alert(visitor ?? "Anonymous");

Code

How does JavaScript double question mark (??) operator works 2

The common use case for the double question mark in javascript ?? is to provide a default value. In the example above, here we show the visitor if its value isn’t null/undefined, otherwise Anonymous. Here’s an example below with a visitor assigned to a name:-

let visitor = "Paul";
alert(visitor ?? "Anonymous"); // Paul (user defined)

Code

How does JavaScript double question mark (??) operator works 3

Output

How does JavaScript double question mark (??) operator works 4

 

How to check if a value exist

Nullish coalescing operators are very useful in Javascript programming language. They allow us to check whether or not something exists without throwing an error. For example,  we want to check if a variable named x has a value assigned to it. If it does, then we assign a new value to it. Otherwise, we return undefined. The code below shows how we would write this logic using the ?? operator.

let y = {
  car : "toyota"
}

// The value of car will remain the same because x.car is not null or undefined
y.car ??= "honda";

// no property named tyre in object y .
// the value of y.tyre will be undefined.
// therefore,  the value of tyre will be assigned.

y.tyre ??= 4;

console.log(y.car)  // toyota
console.log(y.tyre) // 4

Code

How does JavaScript double question mark (??) operator works 5

Output

How does JavaScript double question mark (??) operator works 6

 

Falsy Values

In Javascript, we have about six falsy values in javascript, which are: null, 0, undefined, “”(empty string), NaN, and false. There are instances whereby we just want the preceding expression to be carried out when the first operand returns either null or undefined value. In such a scenario we can’t use the || operator because it does not give room to differentiate between ““(empty string) , false, 0, NaN , null and undefined.  All this are considered as falsy values, but the double question mark ?? nullish coalescing operator does not consider all of them as such.

let result = undefined ?? "Hi sir";
console.log(result); // Hi sir

age= null ?? true;
console.log(age); // true

age = false ?? true;
console.log(age); // false

result = 60 ?? true;
console.log(age); // 60

age = "" ?? true;
console.log(age); // ""

age = NaN ?? true;
console.log(age); // NaN

age = 4 > 5 ?? true;
console.log(age); // false because 4 > 5 evaluates to false

age = 4 < 5 ?? true;
console.log(age); // true because 4 < 5 evaluates to true

age= [4, 5, 6] ?? true;
console.log(age); // [4, 5, 6]

Code

How does JavaScript double question mark (??) operator works 7

It’s clear that the outcome of any operation x ?? y is y only when x is either undefined or null. While in all the other cases, the outcome of the operation will always be x.

 

How to replace values in an array

The double question mark ?? is useful when you want to replace values in an array. Replacing nullish values inside an array is made easy with the operator null coalescing(??) operator. This can be further understood with the help of below code.

<!DOCTYPE html>
<html>
<head>
<title>double questionmark</title>
</head>
<body>
<h1>Hello</h1>
<h2 id="myArray"></h2>
<script>
     let array = [1, 2, "apple", null, undefined, []]
     // Replace each nullish values with "goat"
     array.forEach((item, index)=>{
     array[index] ??= "goat"
     })
     document.getElementById("myArray").innerText = array.toString();
     //console.log(array)
</script>
</body>
</html>

 Output

How does JavaScript double question mark (??) operator works 8

 

Short-circuit Evaluation

Now that we have seen some real-life uses of the ?? operator, let's check out one of its properties called short-circuit evaluation.  Short-circuit evaluation refers to evaluating expressions in order from left to right until the result is known. This means that JavaScript evaluates expressions only once they are needed. Short-circuit evaluation is helpful because it makes programs run faster.

What the above paragraph mean is when JavaScript sees a double question mark ?? expression, if the expression on the right hand side is true, JavaScript will short-circuit and stop right there without evaluating the left-hand side or the second operand. Let's look at the below example where xxx could mean any value. It simply does not matter what the xxx value represent because JavaScript will not evaluate that side of the expression.

How does JavaScript double question mark (??) operator works 9

 

Importance of Short Circuit Evaluation

As a web developer, you can use this short-circuit nature of ?? to your advantage. In the below code example, we have an animal object with a name and number of legs. We only want to console.log the job that the animal has done. The problem we face is that we do not know if our object has the job value. We can use the double question mark operator ?? and short-circuit evaluation to make this easy.

How does JavaScript double question mark (??) operator works 10

What we have done is output the value of animal.job ?? the default string of 'sick animal'. Since animal.job does not exist inside the animal object, the response we get is undefined. Since undefined or null is  falsy, JavaScript will move to the other side of the double question mark ?? and accept the value it finds there. To make this more exciting, let us look at what happens when our animal object has a value for job.

How does JavaScript double question mark (??) operator works 11

This time, animal.job is found. so, the equation will short-circuits and output the value of animal.job (‘provide milk’).

 

Supported browsers 

  • Chrome 85
  • Edge 85
  • Firefox 79
  • Safari 14

 

Conclusion

We have all seen that the double question mark otherwise known as the  nullish coalescence operator  can be represented as x ??= y, or we can also write it as x ?? (x = y). Now javascript checks the first, if it is nullish then the value of y will be assigned to x.

Leave a Comment