In JavaScript the ? operator is used in conditional statements, and when paired with a :, can function as a compact alternative to if...else statement. There are three main uses for the ? operator, two of which you might not used or even heard of ;) Let's learn about them all in detail.
- Ternary Operator (condition ? true : false)
- Optional Chaining (?.)
- Nullish Coalescing (a ?? b)
The ternary operator is basically a shortcut for a traditional if...else statement. Let's compare a ternary operator with a longer if...else statement:
// Ternary Operator
const state = age >= 18 ? 'Adult' : 'Minor'
// If ... else
let state
if(age >= 18) {
state = 'Adult'
else {
state = 'Minor'
}
In 2020, an awesome new feature known as 'optional chaining' was introduced to JavaScript. If say you have code that calls on an object property that doesn't exist, that code will triggers an error at run time. This may be because of a missing or undefined value in your database or from an API:
const wizard = {
name: 'Wizrd of Oz',
age: '1000',
}
wizard.show.trick()
The above code will throw an error "TypeError: Cannot read property ‘trick’ of undefined" at run time. In order to get rid of the runtime error, you can just insert a ? before the period like so.
const wizard = {
name: 'Wizrd of Oz',
age: '1000',
}
wizard.show?.trick()
With that, it will return undefined instead of throwing an error. Optional Chaining is truly a life-changing feature for JavaScript developers.
Before JavaScript introduced default values for functions, everyone used || operator to assign default values to parameters e.g.
function add(a, b) {
let b = b || 1
return a + b
}
const sum1 = add(2) // b is undefined so b = b || 1 => 1
const sum2 = add(3, 4) // b is not undefined so b = b || 1 => 4
But if you use || to provide a default value, you may encounter unexpected behavior if you consider some values as usable (e.g., '' or 0). Let's demonstrate with an example.
const value1 = 0 || 1000;
console.log(value1);
const value2 = '' || 'default string';
console.log(value2);
Here, we have '0' and 1000 in variable value1. If we log its value in the console, we will get 1000, which is weird. Instead of the default string, we should be getting 0, as zero is not undefined or null. So, '||' fails to do the job here. Similarly, it's the same with value2.
If we replace '||' with '??', we will get 0 and an empty string, which is the correct behaviour.
const value1 = 0 ?? 1000;
console.log(value1);
const value2 = '' ?? 'default string';
console.log(value2);
Nullish coalescing works exactly like the logical OR operator, except you will only get the right side value when the left side value is undefined or null. In other words, ?? only allows undefined and null values, not empty strings ('') or 0s.
Now hopefully you understand how the ? operator works in JavaScript :)
Happy coding.
Top comments (0)