Table of contents
Nullish coalescing (??)
nullish coalescing (??
) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
, otherwise returns its left-hand side operand.
const name = null ?? 'Kashif';
console.log(name);
// Expected output: "Kashif"
const num = 0 ?? 42;
console.log(num);
// Expected output: 0
How it is different from boolean ||
operator:
Earlier we used ||
to provide some default value to any variable, it encounters unexpected behavior if we consider some falsy value on the left-hand side operand
In JavaScript, the following values are considered falsy : ( 0, ' ', null, undefined, NaN )
const num = 0 || 42;
console.log(name);
// Expected output: "42"
However, due to ||
being a boolean logical operator, the left-side operand considered 0
as a falsy value and return us 42
, but if we consider 0
, ' '
, NaN
as valid values, the behavior of ||
can cause unexpected consequences.
const count = 0;
const text = "";
const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""
The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null
or undefined
(but no other falsy values) :
const myText = ""; // An empty string (which is also a falsy value)
const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world
const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
Optional chaining (?.)
Optional chaining is a feature in JavaScript that allows us to access the properties of an object and an array or calls a function. it helps us to access properties without having to check whether the object or array is null or undefined first. It is represented by the ?.
and can be used to concisely access deeply nested properties without having to write a long chain of if statements to check for null
or undefined
values.
Syntax :
obj.val?.prop
obj.val?.[expr]
obj.func?.(args)
const animal = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = animal.dog?.name;
console.log(dogName);
// Expected output: undefined
console.log(animal.someNonExistentMethod?.());
// Expected output: undefined
The ?.
is like the .
chaining operator, except that instead of causing an error if a reference is nullish ( null
or undefined
), the expression short-circuits with a return value of undefined
. When used with function calls, it returns undefined
if the given function does not exist.
let's understand it with an example :
const user = {
name: "Jhon",
age: 28,
address: {
street: "Main St",
city: "New Road",
state: "PK",
zip: 10101,
},
};
console.log(user.address.roadNumber.houseNumber);
if we try to access the properties that don't exist we will get an Uncaught TypeError: Cannot read properties of undefined (reading 'houseNumber')
error, We don't want error in real-world projects, instead of error we can get undefined
.
if we use optional chaining here:
console.log(user.address.roadNumber?.houseNumber)
Here we are simply asking JavaScript if roadNumber
exists and if the value of roadNumber
is not null
or undefined
then and then show me the value of houseNumber
.
Optional chaining can also be used to access elements of an array in JavaScript. It works in a similar way to accessing properties of an object, but using the ?.[]
operator instead of the ?.
operator.
const users = [
{ name: "john", age:30 },
{ name: "jane", age:25 },
{ name: "bob", age:35 },
];
console.log(users[3].name); // Uncaught TypeError: Cannot read properties of undefined (reading 'name')
console.log(users[3]?.name); // undefined