Use if
to specify a block of code to be executed, if a specified condition is true
if (condition) {
// block of code to be executed if the condition is true
}
let x = 9;
if (x > 2) {
console.log("x is greater than 2");
}
Use else
to specify a block of code to be executed, if the same condition is false
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
let x = 9;
if (x > 2) {
console.log("x is greater than 2");
}
else {
console.log("x is not greater than 2");
}
Use else if
to specify a new condition to test, if the first condition is false
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
let x = 9;
if (x > 10) {
console.log("x is greater than 10");
}
else if (x > 2) {
console.log("x is greater than 2 but not greater than 10");
}
else {
console.log("x is not greater than 2");
}
Use switch
to specify many alternative blocks of code to be executed
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
let day = "Monday";
switch (day) {
case "Monday":
console.log("It's the start of the week");
break;
case "Sunday":
console.log("It's weekend");
break;
default:
console.log("It's a regular day");
}
let age = 19;
let message = (age >= 18) ? "You are ready to vote" : "You cannot vote";
console.log(message);
Truthy
and Falsy
Values:let truthyValue = "Hello"; // Truthy
let falsyValue = 0; // Falsy
if (truthyValue) {
console.log("Truthy value");
}
if (!falsyValue) {
console.log("Falsy value");
}