Borislav Hadzhiev
Last updated: Oct 30, 2021
Check out my new book
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.
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.
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 ran.
If you need to check if a value is not equal to zero, you can use the strict inequality (!==) operator.
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.
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.