Javascript: Comparison Operators and Conditional Statements

Please follow & like us :)

Comparison Operators:

OperatorDefinitionExample
Equal (==)Returns true if the values of the variables are equal.let var1 = 3;
let var2 = '3'

(var1 == var2) returns true
Not equal (!=)Returns true if the values of the variables are not equal.let var1 = 3;
let var2 = 4;
(var1 != var2) return true.
Strict equal (===)Returns true if the values and type of the variables are equal.let var1 = '3';
let var2 = '3';
(var1 == var2) returns true
Strict not equal (!==)Returns true if the values of the variables are of the same type but not equal, or are of different type.let var1 = '3';
let var2 = 3;
(var1 !== var2) returns true
Greater than (>)Returns true if the left side variable is greater than the right side variable.let var1 = 6;
let var2 = 5;
(var1 > var2 ) returns true.
Greater than or equal (>=)Returns true if the left side variable is greater than or equal to the right side variable.let var1 = 5;
let var2 = 5;
(var1 >= var2 ) returns true.
Less than (<)Returns true if the left side variable is less than the right side variable.let var1 = 4;
let var2 = 5;
(var1 < var2 ) returns true.
Less than or equal (<=)Returns true if the left side variable is less than or equal to the right side variable.let var1 = 4;
let var2 = 4;
(var1 <= var2 ) returns true.

Conditional Statement: Switch

switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}

The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.

function testNum(a) {
   if (a > 0) {
     return "positive";
   } else {
     return "NOT positive";
   }
 }
 console.log(testNum(-5));
 // expected output: "NOT positive"

If Elseif statement for multiple conditions:

if (condition1)
  statement1
else if (condition2)
  statement2
else if (condition3)
  statement3
...
else
  statementN