JavaScript: ternary operators and nullish coalescing
optional shorthand ways of writing some if/else statements
Introduction
As a beginner, you might write something like this:
Ternary operators
To avoid if { // one liner } else { // one liner }
structures, we can use the ternary operator to put this branching structure in one line, thereby reducing the number of lines of code:
Nullish coalescing (??)
Even better than ternary operators, we have the nullish coalescing operator which looks like this, when taking the above example:
Nullish coalescing may not work in some browsers such as Internet Explorer, but ternary operators have greater compatibility
Example inspired by this video:
Last updated