Default negative Numbers to Zero using JavaScript


Borislav Hadzhiev

Last updated: Dec 23, 2021


Photo from Unsplash

Default negative Numbers to Zero in JavaScript #

Use the Math.max() function to default negative numbers to zero, e.g. Math.max(-5, 0). The Math.max() function takes two or more numbers as parameters and returns the largest of the provided numbers.

const num1 = Math.max(-5, 0); console.log(num1); // 👉️ 0 const num2 = Math.max(10, 0); console.log(num2); // 👉️ 10

The Math.max function takes two or more numbers as parameters and returns the largest.

By passing zero as a parameter to the function, we can be sure that the min value the function returns will be 0.

If on the other hand the number is greater than zero, the Math.max function will return the number as is.

An alternative solution is to use the ternary operator.

let num = -5; num = num < 0 ? 0 : num; console.log(num); // 👉️ 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).

In our particular example, if the num variable stores a number that is less than 0, the expression before the question mark returns true, so we return0.

If the expression returns false, we return the number stored in the num variable.

While this solution is intuitive, I find it a bit harder to read than using the Math.max method.

An alternative approach is to use a simple if statement.

let num = -5; if (num < 0) { num = 0; } console.log(num); // 👉️ 0

Declaring the num variable with the let keyword allows us to reassign it if the stored value is less than 0.

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.