Which equals operator should I use in JavaScript?

There will come a point when you want to compare things in JavaScrupt. Is temperature equal to 40? JavaScript provides us two ways to check this. We speak of strict equality and abstract equality.

Comparing the comparison operators

Strict equality (operator ===) will return true if the two candidates we are comparing refer to the same object, or if they have the same type and value. This mean that 40 === 40 will return true, both are integers and both have the value 40. However, 40 === "40" will return false, since 40 is an integer but "40" on the other hand is a string.

Abstract equality (operator ==) will return true if the two candidates we are comparing refer to the same objec, no difference from strict equality here, or if one of them can be casted to the other to get the same type and value. This mean that when using the abstract equality to compare 40 == "40", it will return true.

Consider the code:

console.log("temperature == 40: " + (temperature == 40));
console.log("temperature == "40": " + (temperature == "40"));
console.log("temperature === 40: " + (temperature === 40));
console.log("temperature === "40": " + (temperature === "40"));

The output from this is:

   temperature == 40: true
   temperature == "40": true
   temperature === 40: true
   temperature === "40": false

The recommended way is to stick with strict equality (===) to avoid bugs and misunderstandings.

Enjoyed this article? Give the teacher an apple.

cookie

0

Author

authors profile photo

Articles with similar tags

Comments