Skip to content

JavaScript equality operator | Code

JavaScript equality operator is used to check whether its two operands are equal, returning a Boolean result.

x == y

The === and == operators evaluate whether one value is equal to another == will also check if the values are equal after one of the values is converted into another type.

Note: The strict equality operator attempts to convert and compare operands that are of different types.

JavaScript equality operator

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
   console.log(1 == 1);
   console.log('hello' == 'hello');
   console.log('1' ==  1);
   console.log(0 == true);
 </script>
</body>
</html>

Output:

JavaScript equality operator

Other examples

console.log("string" === "string"); // -> true
console.log(1 === 1); // -> true
console.log(1 === "1"); // -> false
console.log(1 == "1"); // -> true
console.log("String" === "string"); // -> false
console.log("String" == "string"); // -> false

Comparison with no type conversion

1 == 1;              // true
"hello" == "hello";  // true

Comparison with type conversion

"1" ==  1;            // true
1 == "1";             // true
0 == false;           // true
0 == null;            // false
0 == undefined;       // false
0 == !!null;          // true, look at Logical NOT operator
0 == !!undefined;     // true, look at Logical NOT operator
null == undefined;    // true

const number1 = new Number(3);
const number2 = new Number(3);
number1 == 3;         // true
number1 == number2;   // false

Comparison of objects

const object1 = {"key": "value"}
const object2 = {"key": "value"};

object1 == object2 // false
object2 == object2 // true

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Answer: Using the == operator (Equality)

true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2;  //true, because "2" is converted to 2 and then compared

Using the === operator (Identity)

true === 1; //false
"2" === 2;  //false

This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.

On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.

Do comment if you have any doubts or suggestions on this JS operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading