Conditional Statements
Sometimes you have to take actions based on the user's input or maybe you have to run a block of code based on conditions, in that case, we can use conditional statements.
There are 4 types of conditional statements :
if statement
it is used to execute a block of code only if the condition is true.
Syntax:
if (condition ===true){
//block of code to be executed
}
Example:
if (age>=18){
console.log("you can drive")
}
if-else statements
it is used to execute a block of code if you don’t know whether the condition is true or false. It helps you run two different blocks of code based on their boolean value.
Syntax:
if (condition===true){
//code to be executed
}
else{
//code to be executed
}
Example:
let time = 5
if (time>=20){
console.log("good night")
}
else{
console.log("good morning")
}
if- else if-else statements
It is used to check multiple conditions and only executes the block whose boolean value is true. If all conditions are false then it runs the else block of code.
Syntax:
if (condition===true){
//code to be executed
}
else if (condition===true){
//code to be executed
}
else{
//code to be executed
}
Example:
let time=10
if (time<12){
console.log("Good Morning")
}
else if (time>=12 && time <16){
console.log("Good Afternoon")
}
else if (time>=16 && time <=20){
console.log("Good Evening")
}
else if (time>20 && time <=24){
console.log("Good Night")
}
else{
console.log("you have entered the wrong time")
}
switch statements
A switch statement can replace multiple if checks. It gives a more descriptive way to compare a value with multiple variants.
Syntax:
switch(x) {
case 'value1': // if (x === 'value1')
//code to be executed
break;
case 'value2': // if (x === 'value2')
//code to be executed
break;
default:
//code to be executed
break;
}
Example:
let a = 2 + 2;
switch (a) {
case 1:
alert( 'Too small' )
break;
case 2:
alert( 'Exactly!' )
break;
case 3:
alert( 'Too big' )
break;
default:
alert( "I don't know such values" )
break;
}