Skip to content

Conditions

The conditional structure allows code to be executed only if a condition is true.
In English, it can be read as: “If … then … else …”

let age = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}

Here, if the variable age is greater than or equal to 18, it prints “Adult”.
Otherwise, it prints “Minor”.


else if allows testing multiple conditions in sequence.
The program stops as soon as one condition is true.

let grade = 15;
if (grade >= 16) {
console.log("Excellent");
} else if (grade >= 10) {
console.log("Average");
} else {
console.log("Fail");
}

If the grade is 15:

  • The 1st condition (grade >= 16) is false
  • The 2nd condition (grade >= 10) is true → it prints “Average”.
  • The last one is not evaluated.

switch is an alternative to multiple if/else if statements, more readable when comparing a single variable against multiple possible values.

let day = "Tuesday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Almost the weekend");
break;
default:
console.log("Regular day");
}
Warning

Without break, execution continues into the following cases (fallthrough effect). The default block runs if no case matches.


  • If / Else: ideal for testing complex conditions (age > 18 && license === true).
  • Switch: more readable when testing one variable against several fixed values (day === “Monday”, day === “Tuesday”, etc.).

let role = "admin";
if (role === "admin") {
console.log("Full access");
} else if (role === "editor") {
console.log("Limited access: editing allowed");
} else {
console.log("Restricted access: read only");
}