Conditions
If / Else
Section titled “If / Else”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
Section titled “Else If”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
Section titled “Switch”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.
Quick comparison
Section titled “Quick comparison”- 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.).
Practical example
Section titled “Practical example”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");}