Javascript Comparisons

In this chapter we will learn about Comparison.

As we have told, the Comparisons are operators for determine equality or difference between variables or values.

I'm sure you have seen a thing like this. For example y = 10. This operator is not comparison. It's for setting value to a given variable.

Let's look at the table, to know which type of comparisons there are.

Operator Description Comparing Returns
== equal to x == 8
x == 5
false
true
=== equal value and equal type x === "5"
x === 5
false
true
!= not equal x != 8 true
!== not equal value or not equal type x !== "5"
x !== 5
true
false
>  greater than x > 8 false
<  less than x < 8 true
>=  greater than or equal to x >= 8 false
<=  less than or equal to x <= 8 true

How to use it?

The Comparison is used to compare any values and do something depending on the result.

if (speed > 120){
       variable = "Is very fast";
}

Logical Operators

Logical operators are operators to determine a logic of 2 values. Let's set values to the variables: x = 10, y = -8.

There are 3 Logical operators.

  • && (and) -- (x > 5 && y < -7) is true
  • || (or) -- (x > 10 || y == 9) is false
  • ! (not) -- !(x > y) is false

Conditional Operator

Conditional Operator is very useful syntax for programmer. It's very correct code style.

variableName = condition ? value1 : value2 
// value1, when condition is true, value2 when condition is false

var name = girl ? 'Ani' : 'Tigran';

Operator for Bits

As you know the programming is based on {0,1} and every programming language has operators to work with bits. Javascript has these operators too.

Operator Description Example Same as Result Decimal
& AND x = 5 & 1 0101 & 0001 0001 1
| OR x = 5 | 1 0101 | 0001 0101 5
~ NOT x = ~ 5  ~0101 1010 10
^ XOR x = 5 ^ 1 0101 ^ 0001 0100 4
<< Left shift x = 5 << 1 0101 << 1 1010 10
>> Right shift x = 5 >> 1 0101 >> 1 0010 2