Have you seen a question mark (?) in JavaScript code but you don’t know what it means? What if I tell you the question mark can have not only one meaning, but three different meanings in JavaScript based on how it is used? All of the sudden, the question mark can sound complicated. However, once you know what it is, you will start using it often on your codebase. After, what does the question mark mean?
Depending on the context being used, the question mark (?) in JavaScript can work in three different ways:
- As a Ternary Operator
- As a Null Coalescing Operator
- As Optional Chaining Operator
This article will explain and demonstrate how the question mark (?) operator works as a ternary operator, as a null coalescing operator, and as an optional chaining operator.
Table of Contents
How does the question mark (?) work as a Ternary Operator?
The question mark (?) used in the ternary operator separates the expression to be evaluated and the statement to be executed if the expression is true. And the colon operator (:) separates the statements in the truth block and the statements in the false block.
The term “ternary” means associated with three elements. Now, you might get your answer why the operator is called ternary. Yes, it is because the operator takes three operands: the condition, the truth block, and the false block. Let’s look at the syntax below to get a clear view of it.
condition ? statement1 : statement2
If the condition
is true, then statment1
will get executed, and if the condition
is false, then statement2
will get executed. Let’s implement a conditional check with the ternary operator.
const age = 20;
age >= 18 ? console.log("You are eligible to vote") : console.log("You are not eligible to vote")
//prints "You are eligible to vote
Let’s consider 18 as the minimum legal age to vote. The above program shows the voting eligibility for the age of 20. In contrast to the if–else statement, the job gets done in one line and is more readable. Now, it makes sense how the ternary operator is a short-hand alternative to the if–else statement.
In JavaScript, apart from false, some other expressions also represent the falsy values. These are
- null
- NaN
- 0
- the empty string (“”)
- undefined
If these expressions are evaluated in the ternary operator, the false block will get executed. Let’s see an example below.
let person = ""
name = person ? person : `user`
console.log(`hey ${name}`) // "hey user"
In the example above, since the person
variable is empty, the variable is evaluated as false, and the false block is executed.
How does the question mark (?) work as a Nullish Coalescing Operator?
Another scenario where the question mark (?) is used in JavaScript is in the null coalescing operator. The two question mark symbol (??) forms the null coalescing operator. The operator takes two operands on either side. The expression returns the right-hand side operand if the left-hand side operator is null
or undefined
. If it is not the case, the expression returns the left-hand side operator. The syntax of the operator is shown below.
statement1 ?? statement2
Here, statement2
will be evaluated only if statement1
is null
or undefined
; else, statement1
will be evaluated. The need for the null coalescing operator rises when a default value is needed in case the required value is unavailable. For example, let’s consider an application where the user needs to upload their profile picture. If the user has not uploaded their picture, the null coalescing operator can be used to upload a dummy picture. Let’s see the example of the null coalescing operator.
let person = null
const name = person ?? 'user'
console.log(`hey ${name}`) // "hey user"
Here, the person
variable has a null
value. As a result, the name variable in the second line holds the value “user”, which is its right-hand side operand. If the person
variable had any other value instead of null
or undefined
, it would evaluate that value. The example is shown below.
let person = "Harry"
const name = person ?? 'user'
console.log(`hey ${name}`) // "hey Harry"
Now, you might wonder how the null coalescing operator works if the left-hand side operand has a false
or an empty value. Yes, this is a contrasting behavior of this operator compared to the ternary operator. The null coalescing operator will return the left-hand side operand even though they are falsy or have an empty value. It is because these values are neither null
nor undefined
. Let’s see the example below to understand this behavior.
let person1 = ""
const name1 = person1 ?? 'user'
console.log(`hey ${name1}`) // "hey "
let person2 = false
const name2 = person2 ?? 'user'
console.log(`hey ${name2}`) // "hey false"
How does the question mark (?) work as a Optional Chaining Operator?
The optional chaining operator (?.) provides a way to check the values of nested objects in a chain of objects without explicitly checking whether each object is null or undefined. If any reference in the chain is null or undefined, instead of an error message, undefined
is returned. There is no need to check whether each reference is null
and undefined
in the chain of objects. Thus, it provides a short and concise way to access the deep-nested object in a chain of objects.
As you have already known the ternary operator, let’s understand the working mechanism of the optional chaining operator represented using the ternary operator.
let user = {}
let name = (user !== null || user !== undefined) ? user.name: undefined;
console.log(name)
The translation of the above code snippet using optional chaining is shown below.
let user = {}
let name = user?.name
console.log(name)
Since the user
object is null
, the optional chaining returns undefined.
An error message will be shown when you use the chaining operator (.) to access the property that does not exist within an object.
let country = {}
console.log(country.state.city) // TypeError: country.state is undefined
In such a situation, you can use the optional chaining as follows.
let country = {}
console.log(country?.state?.city) // undefined
Instead of showing an error, it returns undefined
.
If it weren’t for the optional chaining, you would not be able to write such elegant expressions. Let’s consider an example where you use the logical AND operator (&&).
let country = {}
console.log(country && country.state && country.state.city) // undefined
In the example above, there is the repetitive use of the country
and country.state
objects. The use of optional chaining eliminates the problem.
Conclusion
The question mark (?) is used in various operators in JavaScript like the ternary operator, null coalescing operator, and the optional chaining operator. In this article, you learned how the question mark (?) fits in these operators. You also came to know how these operators work and simplify the tasks while evaluating different expressions in JavaScript.
Did this article help you understand how the question mark (?) works in JavaScript?
Let us know by replying on Twitter of Become A Better Programmer or to my personal Twitter account.