DEV Community

Cover image for Comparison & Equolity Operators

Comparison & Equolity Operators

Operators are the symbols in between two operands.
They are essential in a programming language for performing various operations including arithmetic, logical, bitwise, conditional, and so on.
Operators in JavaScript are used to compare two values to determine if an expression is true or false.

πŸ›‘ πŸ’‘ Points to keep in mind:

JavaScript includes operators that perform some operation on single or multiple operands (data value) and produce a result.

The Operators in JavaScript are helpful in comparing values, assigning values, performing arithmetic and logical operations, and so on.

Let's consider a very simple expression 3 * 7 = 21. Here, 3 and 7 are ''operands'' and ''*'' is an operator.

πŸ”»

JavaScript includes various categories of operators:

  • Arithmetic operators,
  • Comparison operators,
  • Logical operators,
  • Assignment operators,
  • Conditional operators(Ternary operator ?:)
  • Bitwise Operators
  • Unary operators
  • Relational operators
  • Comma operator

πŸ‘‰ In this article, I will focus on comparison (relational) and equality operators – they are the two most common types of operators you will encounter in JavaScript.

Comparison Operators

There will be times in creating logic to solve problems that you will need to use comparison or relational operators to conditionally render something to the screen. Let’s take a look at the most common ones you will see in your code. Here is the object we will use for the next few operators:

in
– use the in operator to see if there is a property in your object:

const cityData =  {
     city: "Berlin",
     country: "Germany",
     area: 891.8,
     land: 891.8,
     water: 3.12,
     urban: 3,769,495,
     metro: 6,144,600,
     elevation: 34,
     population: 3,769,495,
     timezone: "Berlin/Europe",
     website: "www.berlin.gov"
}
console.log("metro" in cityData); //true
console.log("country" in cityData); //false

Enter fullscreen mode Exit fullscreen mode

instanceof
– use the instanceof operator to ask if an object is an instance of a class or constructor function

  function Class(subject, teacher, numStudents) {
     this.subject = subject;
     this.teacher = teacher;
     this.numStudents = numStudents;
   }
   const classroom = new Class('JavaScript', 'Irene Doe', 26);

   console.log(classroom instanceof Class);
   // expected output: true

   console.log(classroom instanceof Object);
   // expected output: true
Enter fullscreen mode Exit fullscreen mode

Less than ( < ),
Less than or equal to ( <= )

– A comparison operator that returns true in a conditional statement if operand A is less than operand B.
It is most commonly when we create a for loop:

    for(let i = 1; i <= n; i++) {
        // code here
        }
    for(let i = 0; i < arr.length; i++) {
        // code here
    }

Enter fullscreen mode Exit fullscreen mode

Greater than ( > )
Greater than or equal to ( >= )

– A comparison operator that returns true in a conditional statement if operand A is greater than operand B. It’s used quite often when we are trying to find the maximum number in an array:

let maximum = -Infinity;
    for(let i = 0; i < arr.length; i++) {
          if(arr[i] >= maximum) {
          maximum = arr[i];
        }
      }
Enter fullscreen mode Exit fullscreen mode

πŸ›‘ Attention: >= is not the same as =>.
The latter is used for big arrow functions in ES6 JavaScript syntax.

Equality Operators πŸ€”

Similar to comparison operators, equality operators also evaluate to a Boolean value that declares whether or not an expression is true.

Equality ( == ) vs. Identity ( === )

– When we see equal signs ( = ) in JavaScript, one equal sign is an assignment operator and not what we were used to when we were in math class.

  • Two equal signs is strictly an equality operator. It only checks to see if the values are equal by attempting to convert the values to the other’s data type. This is called type coercion.
console.log(8 == '8'); //true

Enter fullscreen mode Exit fullscreen mode

Similarly, if we see a bang/exclamation point along with one equal sign ( != ), known as the inequality operator, it compares two values to see if operands are not equal in number. It doesn’t check for type.

console.log(8 != '4'); //true
Enter fullscreen mode Exit fullscreen mode

Conversely, the identity operator, three equal signs ( === ), checks for type and number when comparing the two values.

console.log(8 === '8'); //false
console.log(8 === 8); //true
Enter fullscreen mode Exit fullscreen mode

Just like the inequality operator, the nonidentity operator ( !== ) checks to see if the operands are unequal. In addition, it checks the type as well. If they are, the condition is true and will return true. If not, it will return false.

console.log(8 !== '8'); //true
console.log(8 !== 8); //false
Enter fullscreen mode Exit fullscreen mode

Summary

Comparison and equality operators are essential to constructing logic in programming.
When we compare the left operand with the right operand, we use equality operators to see if the values are equal in type, not in type, in type and number, or not in type and number.

In addition, we use the comparison operators to help with the logic that will render a user interface (UI). When you feel comfortable with these operators, check out logical operators, the ternary operator, and bitwise operators!

Happy Coding!

Top comments (4)

Collapse
 
pentacular profile image
pentacular

Equality ( == ) vs. Identity ( === )

Just pointing out that === is not the identity operator.

The === uses the Strict Equality Comparison algorithm, as opposed to == which uses the Abstract Equality Comparison algorithm.

You can easily tell that === is not an identity operator by considering a case like this:

console.log(NaN === NaN);
// False

I'm not sure where the idea that === is an identity operator comes from, but I've seen this mistake repeated many times. :)

Collapse
 
irenejpopova profile image
Irena Popova πŸ‘©πŸ»β€πŸ’»

JavaScript is performing the equality evaluation. The interpreter first converts both operands to the same type. Then executes the identity comparison.

The identity evaluation algorithm ( ===) some rules

  1. If both operands have different types, they are not strictly equal
  2. If both operands are null, they are strictly equal
  3. If both operands are undefined, they are strictly equal
  4. If one or both operands are NaN, they are not strictly equal
  5. If both operands are true or both false, they are strictly equal
  6. If both operands are numbers and have the same value, they are strictly equal
  7. If both operands are strings and have the same value, they are strictly equal
  8. If both operands have reference to the same object or function, they are strictly equal
  9. In all other cases operands are not strictly equal.

NaN in identity (and in equality) operator compared with any other value always evaluates to false. Let's consider some examples. It’s the best way to remember the strict comparison algorithm.

1 === "1" // false,  

Operands are different types (number and string) and based on rule 1 they are not identical.

0 === 0 // true,  rule  6

Operands are the same type (number) and have the same value, so they are strictly equal based according to the rule in line 6.

undefined === undefined // true,  rule 3

Both operands are undefined and applying rule 3 it’s an equality.

undefined === null // false,  rule 1 

Because operands are different types, based on rule 1 they’re not identical.

NaN === NaN // false,  rule 4 on line 4  -
// identity evaluation algorithm

Operands are the same type (numbers), but the rule 4 indicates than nothing is equal with a NaN. The result isfalse.

var firstObject = {},
  secondObject = firstObject;
secondObject['name'] = 'Tom';
secondObject === firstObject // true, based on  rule 8

Both variables firstObject and secondObject are references to the same object and based on rule 8 the identity operator evaluates to true.

[ ] === [ ] //false,

The [ ] literal creates a new array reference.
Both operands being the same type (object), however have reference to different objects. rule 9 says that the identity evaluates to false.

Collapse
 
pentacular profile image
pentacular

NaN in identity (and in equality) operator compared with any other value always evaluates to false

Again, if NaN === NaN is false, === cannot be an identity operator. :)

Both operands being the same type (object), however have reference to different objects

You'll note that your rules have no "reference to" in them.

[] and [] just have different values - the value of an object is not determined by its properties.

Collapse
 
macsikora profile image
Pragmatic Maciej • Edited

Both are equality operators. One exists because of the failure of the second. I would say == is equality with type coercion === is equality without type coercion.