DEV Community

Cover image for Nullish coalescing operator (??) & Optional chaining operator (?.)
dev-ashishsethi
dev-ashishsethi

Posted on

Nullish coalescing operator (??) & Optional chaining operator (?.)

As a beginner when writing your JS code you may thought about how to handle null or undefined values especially if it is in a condition. Here Nullish coalescing comes into play.

Didn't understand anything?

Nullish coalescing operator (??)

Nullish coalescing operator (??) is a logical operator just like the OR(||) operator. If operation on left hand side returns null or undefined then right hand side operation is executed. If left hand side operation is not null or undefined then only left hand side operation is performed.

Code example:
example 1:

const testVariable= null ?? 'default string';
console.log(testVariable);
// output: "default string"

example 2:
const testVariable2= 0 ?? 42;
console.log(testVariable2);
// output: 0

This operator cannot be used with OR or AND operator, if you use it then you will get a syntax error.

If you still want to use OR and AND operator with nullish coalescing operator then use parentheses around OR or AND operator

example:
(null || undefined) ?? "hello world!";

Optional chaining operator(?.)

When there are chances that the value of an object can be null or undefined then this operator is used.

code example:

let obj = { prop: "hi" };
console.log(obj.prop?.toUpperCase());

Top comments (0)