What is the difference between == and === in JavaScript?

In JavaScript, "==" and "===" are comparison operators used to compare values or variables.

The main difference between them is that "==" (double equals) checks for equality of values, whereas "===" (triple equals) checks for both equality of values and types.

When using "==" to compare two values, JavaScript will attempt to convert the types of the values if they are different, before making the comparison. This is known as type coercion. For example, the following code will return true:

5 == "5"   // true

In this example, the string "5" is converted to a number before the comparison.

Here's an example of using the "==" operator in JavaScript:

let num = 5;
let str = "5";

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

In this example, we declare two variables: "num" and "str". Although "num" is a number and "str" is a string, we use the "==" operator to compare them. Because of type coercion, JavaScript will convert the string "5" to a number before making the comparison. Therefore, the output of this code will be "num and str are equal".

On the other hand, "===" will only return true if both the values being compared have the same type and value. For example:

5 === "5"  // false

In this case, the comparison returns false because the type of the two values is different.

Here's an example of using the "===" operator in JavaScript:

let num = 5;
let str = "5";

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

In this example, we have the same two variables: "num" and "str". However, instead of using the "==" operator, we use the "===" operator to compare them. Unlike the "==" operator, the "===" operator will not perform type coercion. Since "num" is a number and "str" is a string, they have different types and are not equal using the "===" operator. Therefore, the output of this code will be "num and str are not equal".

Next > Difference Between =, == And === In JavaScript.

It is generally recommended to use "===" over "==" in most cases to avoid unexpected behavior due to type coercion.