Understanding Control Flow in JavaScript: A Complete Beginner's Guide
By default, JavaScript code executes line-by-line from top to bottom. However, in real-world application development, you often need to alter this execution order based on specific dynamic conditions or function calls. This mechanism of controlling the execution flow of code is known as Control Flow.
What is Control Flow?
Control flow refers to the order in which the JavaScript engine executes statements in a script. When a function is called, the execution skips directly to the body of that function. Once the function finishes running, JavaScript returns to the line following the original function call and continues line-by-line execution.
JavaScript provides several built-in keywords to manage this execution flow:
if
else / else if
switch / case
break
continue
Ternary Operator (? :)
Conditional Statements
1. if Statement
The if statement executes a block of code only if a specified condition evaluates to true. Note that if is a reserved keyword in JavaScript and cannot be used as a variable name.
let score = 85;
if (score >= 80) {
console.log("You passed!"); // Executes because condition is true
}
2. else Statement
The else statement specifies a block of code to run when the if condition evaluates to false. An else block cannot exist independently; it must always follow an if statement.
let age = 16;
if (age >= 18) {
console.log("Eligible to vote.");
} else {
console.log("Not eligible to vote."); // Executes because age < 18
}
3. else if Statement
When you need to test multiple conditions sequentially beyond a simple binary choice, use else if.
let mark = 75;
if (mark >= 90) {
console.log("Grade A");
} else if (mark >= 70) {
console.log("Grade B"); // Executes
} else {
console.log("Grade C");
}
The switch Statement
The switch statement evaluates an expression and matches its evaluated value against several case clauses. It offers a cleaner structure than long else if chains when comparing a single expression against fixed values.
Key Components:
case: Defines a value to compare against the expression.
break: Terminates the switch block. Without a break, execution "falls through" into subsequent cases regardless of whether they match.
default: Runs when none of the specified cases match the given expression.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Friday":
console.log("Weekend is near.");
break;
default:
console.log("Mid-week day.");
}
Ternary Operator
The Ternary Operator serves as a shorthand alternative to a basic if...else statement. It takes three operands and returns a value based on the condition.
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
Example:
let isLoggedIn = true;
let message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message); // Output: Welcome back!
