🎄JS Advent #5 - Strict vs loose equality🎄

jtlavs

James L

Posted on December 6, 2022

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

💖 💪 🙅 🚩
jtlavs
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.

Related

How JavaScript works
javascript How JavaScript works

November 8, 2024

A Beginner's Guide to JavaScript Closures
javascript A Beginner's Guide to JavaScript Closures

November 5, 2024

Type Coercion in JavaScript Explained
javascript Type Coercion in JavaScript Explained

November 18, 2024

Introduction to Asynchronous JavaScript
javascript Introduction to Asynchronous JavaScript

October 14, 2024

Strings -- Manipulating the Immutable.
javascript Strings -- Manipulating the Immutable.

November 15, 2024