DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

James L
James L

Posted on

πŸŽ„JS Advent #5 - Strict vs loose equalityπŸŽ„

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
Enter fullscreen mode Exit fullscreen mode

This also will return true:

console.log('1' == 1); // true
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

But it will not perform a type conversion prior to the comparision:

console.log('1' === 1); // false
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

Rust language vs others

Stop by this week's meme thread!