Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Member-only story

Stop Using Logical OR, Use ?? Instead

4 min readJun 10, 2022

--

Press enter or click to view image in full size
Don’t use logical OR, Using Null Coalescing operator
Seriously. Stop using the logical OR when you’re not writing boolean

JavaScript has a very flexible syntax; you can use the same syntactical expressions in various ways to accomplish different things; this is one of the benefits of programming in JavaScript.

Software developers (in any language) typically use the || operator when evaluating boolean expressions for truth. JavaScript developers can also use it in other ways.

Software often uses default values — also known as fallback values. If data does not exist, then a fallback value is used instead. Before ES2020, developers accomplished this using the logical OR operator.

JavaScript code demonstrating fallback values with the logical OR operator
outOf defaults to 5 if the argument is not provided

Notice how the above code uses the logical OR operator to fall back to 5 if outOf is null or undefined. The above code is a nicer way of writing:

JavaScript code demonstrating a fallback value using conditionals
Using an if-statement for providing a fallback value

--

--

The Soggy Waffle
The Soggy Waffle

Written by The Soggy Waffle

I am a programmer, and I like to make cool things. I enjoy being rude in the comments, so content at your own discretion 😏

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.