JavaScript

JavaScript Question Mark Operator

Normally in any programming language we represent the conditional statements with the traditional “if…else..” but these sometimes take up various lines of codes even for the simpler conditions. Hence, JavaScript provides us with the Question Mark(?) operator used for conditional statements in JavaScript.

The question mark (?) operator in JavaScript is one of the most powerful features that JavaScript provides for conditional statements and when used along “:” it can act as “if…else..”. But that’s not the only way this operator is used in JavaScript. In this article we’ll discuss the question mark operator in JavaScript along with its usage with examples.

Ways to Use Question Mark (?) Operator in JavaScript

The most common way of using the question mark operator is for conditional statements but that’s not the only usage of it in JavaScript. There are three main usages of the question mark operators in JavaScript as shown below:

  1. Ternary Operator
  2. Optional Chaining
  3. Nullish Coalescing

One of which we all are familiar with, but the other two are those only few know about so lets see and understand each along with examples.

Ternary Operator

The term ternary simply means consisting of three parts and the question mark operator is also known as the ternary operator because unlike other operators such as “===” strictly equal, it is the only operator that takes in three parts.

In the ternary operator we start with “?” in which we add a conditional statement on the left side of the operator and a value on the right side of the operator in case the condition is true. It’s followed by a colon “:” which is followed by a value that is to be returned in case the condition is false. Below is the syntax provided:

Syntax:

Conditional Statement ? True(value if true) : False (value if false)

The ternary operator is used to replace the multiple lines of code of if else statement. Below is an example of if else statement along with it being replaced by a ternary operator to show how a conditional statement of if else can be changed to a single line code easily.

if(20>12){
    console.log("Yes")
}
else{
    console.log("No")
}

The above line of code can be converted to a single line code:

const biggerNum = (20 > 12) ? "Yes" : "No";
console.log(biggerNum);

You can clearly see the difference between several lines of if-else condition is turned to a single line code using a ternary operator.

Optional Chaining

Optional Chaining feature was introduced in 2020 that helps the user to handle an error in a more efficient manner. Let’s say you’ve a code that calls an object proprietary which does not exist and hence when the code is executed it’ll generate an error which could be due to missing value in your database or any other reason. For example look at the below example:

const employee = {
    name: "Mark",
    workingSince: 2015
}
employee.write.salary();

Here, we’ve not defined the properties for the object and hence when we execute the code it’ll generate the below error:

Now to avoid such errors, optional chaining was introduced through which we simply insert a question mark operator “?” between the property names as shown below:

const employee = {
    name: "Mark",
    workingSince: 2015
}
employee.write?.salary();

Output:

Through optional chaining it simply gave output “undefined” instead of throwing any errors and hence it’s one of the best features for developers to avoid such errors more efficiently.

Nullish Coalescing

Sometimes we do not have a value for a property or it’s not available while writing the code. For example if we’re defining various users and we’ve a property image for each user and we don’t have the image available for those users. So, when the data is displayed the images for users will be blank which might look ugly and unprofessional.

const employee = {
    name: "Mark",
    picture: undefined || "N/A"
}
console.log(employee);

Output:

But while dealing with “||” the logical operator OR, you might encounter some issues if you consider some values as usable, such as “ “ and “0”. For example we’ve declared a variable with value 0 or an empty string along with “||” logical OR operator, so the operator will consider the value as NULL or undefined and hence it’ll return some default value that we’ve fixed, as shown by the example below:

const example1 = 0 || 'default string';
console.log(example1);


const example2 = '' || 500;
console.log(example2);

Output:

Here in the above example although we’ve set the values of both as 0 and empty string still it’s taking it as null and undefined and displaying the default value that we set. To solve this issue we use Nullish Coalescing or double question marks(??) as shown below:

const example1 = 0 ?? 'default string';
console.log(example1);


const example2 = '' ?? 500;
console.log(example2);

Output:

This way the nullish coalescing is used which only accepts null and undefined values, other than that it always displays the right side values.

Conclusion

Question mark operator in JavaScript is extremely useful as it is not only used for conditional statements but for other useful purposes. In this article we discussed question mark operators in JavaScript along with various ways of using it. First the traditional way is replacing the if-else conditions with it, but there are other ways as well to use it that we discussed in the article. Through question marks operators we can make our code more compact and handle errors in more efficient ways.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.