Borislav Hadzhiev
Thu Dec 23 2021·2 min read
Photo by Warren Wong
Use the ternary operator to convert an undefined
value to zero, e.g.
const result = val === undefined ? 0 : val
. If the value is equal to
undefined
, the operator returns 0
, otherwise the value is returned.
let val = undefined; val = val === undefined ? 0 : val; console.log(val); // 👉️ 0
The
ternary operator
is very similar to an if/else
statement.
The truthy values are all values that are not falsy.
The falsy values in JavaScript are undefined
, undefined
, false
, 0
, ""
(empty string), NaN
(not a number).
val
variable stores an undefined
value, the expression before the question mark evaluates to true
, so the ternary operator returns 0
.If the expression returns false
, we return the value stored in the val
variable.
An alternative approach is to use a simple if
statement.
let val = undefined; if (val === undefined) { val = 0; } console.log(val); // 👉️ 0
Declaring the val
variable with the let
keyword allows us to reassign it if
the stored value is equal to undefined
.
While this approach is a little more verbose, it's still easy to read and intuitive.
Alternatively, you can use the logical OR (||) operator.
let val = undefined; val = val || 0; console.log(val); // 👉️ 0
The logical OR (||) operator returns the value to the right if the value to the left is falsy.
undefined
, we check that the value is falsy. So it could be an empty string, null
, NaN
, etc.An easy way to think about it is - the value to the right of the operator is a fallback in case the value to the left is falsy.