JavaScript Tutorial JavaScript References

JavaScript - comparison operators example



The example below illustrates the usage of JavaScript comparison operators: ==, !=, >, <, >=, <=.

var txt;
txt = "10 == 10: " + (10 == 10) + "<br>";
txt = txt + "10 != 10: "+ (10 != 10) + "<br>";
txt = txt + "10 < 20: "+ (10 < 20) + "<br>";
txt = txt + "10 > 20: "+ (10 > 20) + "<br>";
txt = txt + "10 <= 20: "+ (10 <= 20) + "<br>";
txt = txt + "10 >= 20: "+ (10 >= 20) + "<br>";

The output (value of txt) after running above script will be:

10 == 10: true
10 != 10: false
10 < 20: true
10 > 20: false
10 <= 20: true
10 >= 20: false

The example below illustrates the usage of JavaScript comparison operators: ===, !==.

var X = 10, Y = 10, Z ="10";
var txt;

txt = "typeof(X): " + typeof(X) + "<br>";
txt = txt + "typeof(Y): " + typeof(Y) + "<br>";
txt = txt + "typeof(Z): " + typeof(Z) + "<br><br>";
txt = txt + "X === Y: " + (X === Y) + "<br>";
txt = txt + "X === Z: " + (X === Z) + "<br>";
txt = txt + "X !== Y: " + (X !== Y) + "<br>";
txt = txt + "X !== Z: " + (X !== Z) + "<br>";

The output (value of txt) after running above script will be:

typeof(X): number
typeof(Y): number
typeof(Z): string

X === Y: true
X === Z: false
X !== Y: false
X !== Z: true

These comparison operators generally return boolean results, which is very useful and can be used to construct conditional statement as shown in the example below:

function range_func(x){
  //&& operator is used to combine conditions
  //returns true only when x >= 10 and x <= 25
  if(x >= 10 && x <= 25)
    return x + " belongs to range [10, 25].<br>"; 
  else
    return x +" do not belongs to range [10, 25].<br>";
}

var txt;
txt = range_func(15);
txt = txt + range_func(25);
txt = txt + range_func(50);

The output (value of txt) after running above script will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

❮ JavaScript - Operators