Set of instructions is called a statement.
These statements will be executed when the condition given is met which means if the given condition is true then statements will get executed. If the condition is false, another statement will be executed.
In JavaScript we have following conditional statements:
if (condition) {
statements
}
let a = true;
if (a) {
console.log("This is true"); // Prints: This is true
}
In above example ‘a is true’ which means condition is met. So, code block will execute. If ‘a is false’ code block will not get execute as shown in below example.
let a = false;
if (a) {
console.log("This is true");
}
if (condition) {
statements
} else {
statements
}
If you want to execute something when the condition is true and to execute something else when the condition is false then we can use if else conditional statement.
let a = false;
if (a) {
console.log("This is true");
} else {
console.log("This is false"); //Prints: This is false
}
if (condition 1) {
statements
} else if (condition 2) {
statements
} else {
statements
}
If you have multiple conditions to check then use if else if conditional statement.
let a = 20;
if (a < 10) {
console.log("a is less than 10");
} else if (a < 30) {
console.log("a is less than 30"); // Prints: a is less than 30
} else {
console.log("a is greater than 30");
}
The switch statement contains multiple cases. A switch statement compares the value of the variable with multiple cases. If the value is matched with any of the cases, then the block of statements associated with this case will be executed.
For which each case, there will be one break which is used to come out of the loop.
This switch will have one default case which will be executed if no case is matched.
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
let dice = 2;
switch (dice) {
case 1:
console.log("you got one");
break;
case 2:
console.log("you got two"); // Prints: you got two
break;
case 3:
console.log("you got three");
break;
default:
console.log("you did not roll the dice");
}