DEV Community

Cover image for Javascript & Question Marks (?)
Husnain Mustafa
Husnain Mustafa

Posted on

Javascript & Question Marks (?)

Let's learn how we can use question marks in javascript to make our code simpler and more readable.

I am going to list down 3 most common used of question marks in js.

Ternary Operator (?)

Most usual use of question mark ? in javascript is Ternary Operator. It is a shorter way of writing condition(if/else). It is applicable in some other languages too.

Syntax:
<condition> ? <if condition satisfies> : <else>

Example:

Application of Ternary Operator

Nullish Coalescing Operator (??)

It returns the value written before ?? only if that value is not null.
If that value is null, it returns the value written after ??

Syntax:
<value> ?? <value>

Example:

Application of Nullish Coalescing Operator

Application of Nullish Coalescing Operator

Optional Chaining (?.)

It is same as chaining objects using dot . but with an exception that if object is undefined, it will not chain further and returns undefined.
It is useful to avoid errors.
It can also be used with arrays

Syntax:

Object:
<identifier>?.<identifier>

Array:
<identifier>?.[<index>]

Example:

Object:
Application of Optional Chaining Operator

Array:
Application of Optional Chaining Operator


That's all. Hope it would help you.
Happy coding.

Top comments (0)