Convert NULL to 0 using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Check out my new book

Convert NULL to 0 using JavaScript #

Use the ternary operator to convert a null value to zero, e.g. const result = val === null ? 0 : val. If the value is equal to null, the operator returns 0, otherwise the value is returned.

index.js
let val = null; val = val === null ? 0 : val; console.log(val); // 👉️ 0

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right is returned.

The truthy values are all values that are not falsy.

The falsy values in JavaScript are null, undefined, false, 0, "" (empty string), NaN (not a number).

If the val variable stores a null value, the expression before the question mark returns true, and the ternary operator returns 0.

If the expression returns false, the operator returns the value that is stored in the val variable.

An alternative approach is to use a simple if statement.

index.js
let val = null; if (val === null) { 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 null.

While this approach is a little more verbose, it's still quite easy to read.

Alternatively, you can use the logical OR (||) operator.

index.js
let val = null; 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.

This means that we don't explicitly check if the value is equal to null, we check that the value is falsy. So it could be an empty string, undefined, NaN, etc.

An easy way to think about it, is that the value to the right of the operator is a fallback in case the value to the left is falsy.

Use the search field on my Home Page to filter through my more than 3,000 articles.