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:
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:
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:
That's all. Hope it would help you.
Happy coding.
Top comments (0)