## Comparison Operators in Javascript

·   ·  ☕ 2 min read

Equals (==), not equals (!=), greater than (>), lesser than (<) - Javascript comparison operators cannot get more simple.

Let’s dissect these operators a bit.

Comparison operators are the ones that you use to.. well, compare.
For example:

 1 2 3 4 5 6 7  let numCoffee = 3; if (numCoffee < 2) console.log("too few"); else if (numCoffee == 2) console.log("just right"); else console.log("crazy"); // output: crazy 

The expression within brackets is evaluated to true or false based on operator precedence.

A succinct representation of the above totally real-world problem will be -

 1 2 3  let numCoffee = 3; console.log(numCoffee < 2); // false console.log(numCoffee > 2); // true 

Equality operator works similar to the above, but has a ‘double equals’ in the expression.

 1 2 3  let numCoffee = 3; console.log(numCoffee == 2); // false console.log(numCoffee == 3); // true 

A single = will result in assignment rather than comparison.

Since we are dealing with Javascript, types can be an advantage or confusing depending on who you ask. To avoid unexpected issues in the above comparison, it is typical to compare the value and the type.

 1 2 3 4  let numCoffee = 2; console.log(numCoffee == "2"); // true console.log(numCoffee === "2"); // false console.log(numCoffee === 2); // true 

The opposite of equality is more prevalent on this planet and is depicted as -

 1 2  let numCoffee = 3; console.log(numCoffee != 2); // true 

When it comes to comparing greater or lesser of the values, it is more common to say ‘greater than or equal to’.

 1 2  console.log(numCoffee >= "2"); // true console.log(numCoffee <= "2"); // true 

You can combine the different operations as well - that is for a different day since I have overdosed on coffees for now.

Stay in touch!
Share on

WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things