🎄JS Advent #5 - Strict vs loose equality🎄
James L
Posted on December 6, 2022
For the month of December I have challenged myself to write 24 articles about JS up until Xmas.
The fifth installment in this series about strict and loose equality.
Double equals (loose equality)
The double equals will compare two values:
console.log('test' == 'test'); // true
console.log(1 == 1); // true
console.log(2 == 1); // false
This also will return true:
console.log('1' == 1); // true
Why is this?
- The double equals (or loose equality) will perform a type conversion.
- Strings are always converted to the Number type to be compared, so in this example the
'1'
string will be coerced to a Number type before the comparison.
Triple equals (strict equality)
- The triple equals will again compare two values:
console.log('test' === 'test'); // true
console.log(1 === 1); // true
console.log(2 === 1); // false
But it will not perform a type conversion prior to the comparision:
console.log('1' === 1); // false
So to compare types always use the triple equals.
In general it is best practice to use the triple equals to avoid any unwanted behavior.
💖 💪 🙅 🚩
James L
Posted on December 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.