Conditional Statements in JavaScript

To perform actions based on conditions, we use conditional statements. There are 2 types of conditional statements in JavaScript.

  1. If condition
  2. Switch case

If condition has 3 sub-types:

  1. If block
  2. If Else block
  3. Nested If block 

If Block : if Conditional Statement

				
					//Syntax:

if (condition) {
    
}

//Example: Print 'Done' in the output if integer 'x' is equal to 100

let x = 100

if (x == 100) {
    console.log("Done")
}

//Note: Line 12 will only be executed if the condition 'x == 100' returns 'true'. As in this case it will be executed as value of 'x' is 100.
				
			

If Else Block : if - else Conditional Statement

				
					//Syntax:

if (condition) {
    
} else {
    
}

//Example: Find bigger of the 2 integers (a and b)

let a = 300
let b = 200

if (a > b) {
    console.log("a is bigger than b")
} else {
    console.log("b is bigger than a")
}

//Note: If the condition 'a > b' returns 'true' then the code in the if block gets executed otherwise the code in else block gets executed.
				
			

Nested If Block : if - else if Conditional Statement

				
					//Syntax:

if (condition) {
    
} else if (condition)  {
    
} else {
    
}

//Example: Find bigger of the 3 integers (a, b and c)

let a = 300
let b = 100
let c = 600

if ((a > b) && (a > c)) {
    console.log("a is the biggest of 3 integers.")
} else if (b > c) {
    console.log("b is the biggest of 3 integers.")
} else {
    console.log("c is the biggest of 3 integers.")
}

/*
Note: If the first condition '((a > b) && (a > c))' returns 'true' 
then the code from the if block gets executed. 
If it returns 'false' then the second condition '(b > c)' is evaluated. 
This continues if multiple 'else if' blocks are used.
*/
				
			

Switch : switch - case Conditional Statement

				
					//Syntax:

switch (key) {
    case value1:
        //code
        break
    case value2:
        //code
        break
        .
        .
    default:
        break
}

/*
Example: Create a simple calculator to perform
Addition, Subtraction and Multiplication on 2 integers.
*/

let num1 = 200
let num2 = 10

let operation = "Multiplication"

switch(operation){
    case "Addition":
        console.log("Addition is: ", (num1 + num2))
        break
    case "Subtraction":
        console.log("Subtraction is: ", (num1 - num2))
        break
    case "Multiplication":
        console.log("Multiplication is: ", (num1 * num2))
        break
    default:
        console.log("Invalid operation")
        break
}

/*
Note: If value of a case matches the switch key then 
the code from that perticular case gets executed.
'break' statement is required to break out of the 
switch case block in JS.
*/