- Courses
- đ»Programming Languages
- đJavaScript
- Foundations
- Control Flow
- If-Else and Switch statements
On this page
Control Flow in JavaScript
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
if-else statementsâ
These are used to perform different actions based on different conditions.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}
switch-case statementsâ
These are used to perform different actions based on different cases.
switch(expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
...
default:
// Code to be executed if expression doesn't match any cases
}
Ternary operator (? ... : ...;)â
This is a shorthand way to write simple if-else statements. It takes three operands: a condition, a statement to execute if the condition is true, and a statement to execute if the condition is false.
condition ? statement_if_true : statement_if_false;
Hereâs an example of how you might use it:
let age = 15;
let type = age >= 18 ? "Adult" : "Minor";
In this example, if age is greater than or equal to 18, type will be âAdultâ. Otherwise, type will be âMinorâ.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Control Flow
Next
Loops
if-elsestatementsswitch-casestatements- Ternary operator (
? ... : ...;)
