JavaScript Comparison Operators

JavaScript Comparison Operators

Comparison operators are used in comparing operands and return a boolean value (true or false). In JavaScript, comparison operators except for the strict equality and inequality operators, convert operands to a common data type when comparing. This is called Type Coercion.

Comparison Operators in Javascript

  • Equality Operator (==)

    a == b would return true if the value of a is equal to the value of b. Otherwise, it would return false.

Example

3 == 3; //true
3 == '3'; //true (type coercion)
1 == 2;  //false
  • Strict Equality Operator (===)

    Unlike the equality operator, the strict equality operator compares values as-is without converting the data types. 3 === '3' would return false because 3 is a number and '3' is a string while 3 === 3 would return true because they are the same data type.

  • Inequality Operator (!=)

    a != b would return true if the value of a is not equal to the value of b. Otherwise, it would return false.

Example

1 != 2; //true
1 != '1'; //false (type coercion makes 1 = '1')
1 != true; //false (1 = true)
0 != false; //false (0 = false)
  • Strict Inequality Operator (!==)

    Whereas 1 != true and 1 != '1' would return false, 1 !== true and 1 !== '1' would return true because the operands are of different data types. This is because Strict Inequality Operator does not convert data types when comparing.

Examples

3 !== 3; //false
3 !== '3'; //true
4 !== 3; //true
  • Greater-than Operator (>)

    a > b would return true if the value of a is greater than the value of b. Otherwise, it would return false.

Examples

5 > 3; //true
'1' > 2; //false (type coercion)
1 > 2; //false
  • Greater-than-or-equal-to Operator (>=)

    a >= b would return true if the value of a is greater than or equal to the value of b. Otherwise, it would return false.

Examples

6 >= 3;  //true
'10' >= 10; //true (type coercion)
1 >= 2;  //false
  • Less-than Operator (<)

    a < b would return true if the value of a is less than the value of b. Otherwise, it would return false.

Examples

5 < 3; //false
'1' < 2; //true (type coercion)
1 < 2 ;//true
  • Less-than-or-equal-to Operator (<=)

    a <= b would return true if the value of a is less than or equal to the value of b. Otherwise, it would return false.

Examples

6 <= 3; //false
'10' <= 10; //true (type coercion)
1 <= 2; //true
  • Logical And Operator (&&)

    num > a && num <= b would return true if both statements are true. Otherwise, It would return false.

Examples

2 > 3 && 2 < 1; //false
2 == '2' && 2 <3; //true
1 <= 3 && 5 > 6; //false
  • Logical Or Operator (||)

    num > a || num <= b would return true if either statements is true. Otherwise, It would return false.

Examples

2 > 3 && 2 < 1; //false
2 == '2' && 2 < 3; //true
1 <= 3 && 5 > 6; //true

Check out the sites below for more information on Comparison in JavaScript