Check if Variable is equal to 0 using JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20211 min read

Check if Variable is equal to 0 in JavaScript #

Use an if statement to check if a variable is equal to zero, e.g. if (myVar === 0). The equality check will return true if the variable is equal to 0 and the if block will run.

index.js
const num = 0; if (num === 0) { console.log('โœ… the variable equals 0'); } else { console.log('โ›”๏ธ the variable does NOT equal 0'); }

We used the strict equality (===) operator to check if a value is equal to 0. The operator returns true if the values on the left and right hand side are of the same type and are equal.

Here are some examples.

index.js
console.log(0 === 0); // ๐Ÿ‘‰๏ธ true console.log(0 === '0'); // ๐Ÿ‘‰๏ธ false console.log(0 === 'zero'); // ๐Ÿ‘‰๏ธ false

If the value is equal to 0, the block in the if statement is executed.

If you need to check if a value is not equal to zero, you can use the strict inequality (!==) operator.

index.js
const num = 100; if (num !== 0) { console.log('โ›”๏ธ the variable does NOT equal 0'); } else { console.log('โœ… the variable equals 0'); }

The strict inequality operator check is the values on the left and right hand side are not equal.

Here are some examples.

index.js
console.log(0 !== 0); // ๐Ÿ‘‰๏ธ false console.log(0 !== '0'); // ๐Ÿ‘‰๏ธ true console.log(0 !== 'zero'); // ๐Ÿ‘‰๏ธ true

If the values are not equal, the condition is met and our if block is ran.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee