Check if Variable is equal to 0 using JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 30, 2021

banner

Photo from Unsplash

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 run.

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 run.

Further Reading #

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.