Comparison Operator

Comparison Operator

Equal (==) and Strict equal (===)

There are many comparison operators in JavaScript and all of these operators return the boolean value true or false. The most common comparison operators are Equality (==) and Strict equality (===) operators.

Equality (==)

The equality operator compares two values for equality and a boolean value true or false is returned depending on whether the two values are equal or not. While comparing the values, JavaScript first attempts to convert the values to a common type i.e. from one data type to another.

For example, when comparing a string and a number using the equality operator JavaScript will attempt to convert the string to a number.

let num = 7;
let str = "7";

if (num == str) {
  console.log("num and str are equal");
} else {
  console.log("num and str are not equal");
}

In this example equality operator compares the num variable with a value of 7 and the str variable with a value of "7" and JavaScript will convert the string "7" to the number 7, and the comparison will return true.

So, the output will be "num and str are equal".

Strict Equality (===)

The strict equality operator compares two values for both value and type equality. It returns a boolean value, either true or false depending on whether the two values are exactly equal or not. This means that the value being compared must be of the same type to be considered equal. If the types are different, the comparison will always return false.

Example of the strict equality operator (===)

let num = 7;
let str = "7";

if (num === str) {
  console.log("num and str are strictly equal");
} else {
  console.log("num and str are not strictly equal");
}

In this example, we have a variable num with a value of 7 and a variable with a value of "7". The strict equality operator compares the two variables, and because the values are not of the same type, the comparison will return false.

So, the output will be "num and str are not strictly equal".

Summary

The equality operator checks for value equality with type coercion. This means that it will attempt to convert the values being compared to a common type before making the comparison.

The Strict equality operator checks for both value and type equality, and does not perform type coercion.