DEV Community

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

Posted on

2

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.

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs