Javascript Comparisons

In Javascript, operators are used to compare two values in terms of equality or difference between them. These can be evaluated by either true or false.

These operator can be logical as well as comparison.

Comparison Operators

These type of operators are used to compare two values on the basis of different operators available.

OperatorDescriptionExample
< less thanif (salary < 4000)
> greater thanif (age > 30)
<=less than or equal toif (salary <= 4000)
>=greater than or equal toif (age >= 30)
==equal toif (day == “Sunday”)
===Equal value and equal typeif (day === “Sunday”)
!=Not equalif (day != “Wednesday”)
!==not equal value or not equal type    if (day !== ” Wednesday “)

These operators also used in conditional statement to compare values and take action on it depending on result.

Input:-
 <script>  
    const age = 10;
    if (age < 18) text = "Age is less than 18";
    document.writeln("(age < 18) evaluated to ",text);
</script>

Output:-

Logical Operators

Logical operators are used to determine the logic between variables or values. They are important in JavaScript because they allow us to compare variables and do something based on the result of that comparison.

For example, if the result of the comparison is true, we perform a block of code; if it’s false, we perform another block of code.

OperatorDescriptionExample
&&And                 (a < 20 && b > 1)
||Or(a < 10 || b > 1)
!Not!(a == b)

Following example illustrate the use of logical operator:-

Input:-
 <script>  
   const a = 10, b = 20;
   if (a > 11 && b < 21){
      document.writeln("(a > 11 && b < 21) is true<br/>");
   } 
   if (a > 11 || b < 21){
      document.writeln("(a > 11 || b < 21) is true<br/>");
   } 
   if (!(a == b)){
      document.writeln("(!(a == b)) is true");
   }
</script>

Output:-

Ternary Operators

Ternary operator contains a conditional operator that assigns a value to a variable based on some condition.

This operator includes three operands: a condition followed by a question mark (?) sign, and two expressions separated by the colon (:). The first expression is executed when the condition is true, and the second expression is executed when the condition is false.

Syntax:-
 var a = (condition) ? expr1 : expr2;  

In the above syntax, condition, expr1, and expr2 are the three operands used in the ternary operator.

Input:-
 <script>  
   let a = 358;  
   let val = ( a % 2 == 0) ? 'Even Number' : 'Odd Number';  
   document.writeln(a + " is " + val);  
</script>

Output:-