Home ยป JavaScript ยป Replace Null with 0 in JavaScript

Replace Null with 0 in JavaScript

To replace a null value with zero, use the ternary operator, as in const result = val === null? 0: val. If the value is null, the operator returns 0, otherwise, it returns the value.

Replacing Null Value with 0 in JavaScript

let val = null;

val = val === null ? 0 : val;

console.log(val); // Output 0

The ternary operator is analogous to an if/else statement.

If the expression to the left of the question mark evaluates to a true value, the value to the right is returned; otherwise, the value to the left is returned. All values that are not false are considered true. In JavaScript, the false values are null, undefined, false, 0, "" (empty string), and NaN. (not a number).

If the val variable is empty, the expression before the question mark returns true, and the ternary operator returns 0. If the expression fails, the operator returns the value stored in the val variable. A simple if statement is an alternative approach.

let val = null;

if (val === null) {
  val = 0;
}

console.log(val); // Output 0

When we declare the val variable with the let keyword, we can reassign it if the stored value is null. While this method is slightly more verbose, it is still quite simple to read. You can also use the logical OR (||) operator.

let val = null;

val = val || 0;

console.log(val); // Output 0

If the value to the left is false, the logical OR (||) operator returns the value to the right. This means that instead of explicitly checking if the value is equal to null, we check if it is false. As a result, it could be an empty string, undefined, NaN, or something else. The value to the right of the operator can be thought of as a fallback if the value to the left is false.

See also: