Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptEquality(==) Comparison Operator in JavaScript

Equality(==) Comparison Operator in JavaScript

In JavaScript, the Comparison Equality Operator is used to compare the values of the operand. The comparison operator returns true only if the value of two operands are equal otherwise it returns false. It is also called a loose equality check as the operator performs a type conversion when comparing the elements. When the comparison of objects is done then only their reference is checked even if both objects contain the same value. 

Syntax: 

a==b

Note: The equality comparison is symmetric in the sense that a==b is the same as b==a.

Example 1: In this example, we will use the equality operator on the same data types.

Javascript




let a = 1;
let b = 1;
let c = new String("Hello");
let d = new String("Hello");
let e = "Hello";
  
console.log(a==b);
console.log(c==d);
console.log(c==e);


Output:

true
false
true

Explanation: Even though c, d, and e are all strings but their comparison in one case returned false because when String is created with the help of Constructor it is treated as an object so when we are comparing c and d two objects are compared and only their reference is being checked which is different but when c is compared with e type conversion takes place and both are compared as a string which returns true.

Example 2: In this example, we will use the equality operator on different data types.

Javascript




let a = 1;
let b = "1";
let c = true
  
console.log(a==b);
console.log(b==c);
console.log(a==c);


Output:

true
true
true

Explanation: The boolean and string values are converted to numbers then comparison takes place so true is returned in all cases

Example 3: In this example, we will compare Date with String using the equality operator.

Javascript




let a = new Date();
let b = a.toString();
console.log(a==b);


Output:

true

Explanation: When the date object is compared with the string it is first converted to a sting so the comparison returns true.

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

We have a complete list of JavaScript Comparison Operators, to check those please go through, the JavaScript Comparison Operator article.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments