Comparison in JavaScript

javascript comparisons
10 November 2024

Comparison in JavaScript is one of the fundamental principles of the language that allows you to perform logical and conditional operations. You can compare two values and investigate whether they are equal or not, whether two types are the same, or whether JavaScript provides the tools you need. Although at first glance these comparisons may seem simple, they contain details that can significantly affect the performance of your programs.

In JavaScript, comparisons are divided into two main categories: comparisons with type coercion, which occur using the operators == and !=, and comparisons without type coercion, which are conducted using the operators === and !==. Choosing the right one between these two methods can prevent unnoticed errors in your code.

For example, when using ==, JavaScript attempts to equalize the types of those values and then performs the comparison. Thus, "5" is considered equal to 5. However, in ===, this is not the case, and both types must be equal as well.

For a better understanding of these comparisons, consider the following example:


let a = 5;
let b = "5";

// with type coercion
if (a == b) {
   console.log("a and b are equal");
} else {
   console.log("a and b are not equal");
}

// without type coercion
if (a === b) {
   console.log("a and b are exactly equal");
} else {
   console.log("a and b are not exactly equal");
}

Code Explanation:

let a = 5;
The variable a is assigned the value 5.

let b = "5";
The variable b is assigned the string "5".

if (a == b)
It is checked whether a and b are equal, with type coercion.

console.log("a and b are equal");
If they are equal, this text is displayed in the output.

if (a === b)
It is checked whether a and b are exactly equal, meaning without type coercion.

console.log("a and b are exactly equal");
If they are equal, this text is displayed, and the opposite text is displayed if they are not.

FAQ

?

Why should we use === instead of ==?

?

Can I directly compare a string and a number?

?

What is type coercion and how does it work?