JavaScriptFunctions & Scope
JavaScript Control Flow (if, else, switch)
Learn JavaScript control flow statements such as if, else if, else, and switch to control decision-making logic in real-world programs.
What is Control Flow in JavaScript?Link to this section
Control flow determines how the execution of a program moves from one statement to another based on conditions.
By default, JavaScript runs code line by line. Control flow statements allow programs to:
- Execute different blocks of code
- Make decisions
- Handle multiple conditions efficiently
The if Statement Link to this section
The if statement executes a block of code only when a condition is true.
Explanation :
If the condition inside if evaluates to true, the code block runs. Otherwise, it is skipped.
The else Statement :
The else statement executes when the if condition is false.
note
"else" must always be associated with an "if"
The else if ladder :
When multiple conditions need to be checked, else if is used.
tip
Conditions are checked top to bottom. The first true condition executes, and the rest are skipped.
Comparison and Logical Operators in ConditionsLink to this section
Control flow statements often use:
- Comparison operators (>, <, ===)
- Logical operators (&&, ||)
The switch Statement :
The switch statement is used when you need to compare one value against multiple fixed cases.
Explanation:
- case checks the value
- break stops execution
- default runs when no case matches
warning
If break is missing, execution will continue into the next case (fall-through).
When to Use if–else vs switchLink to this section
Use if–else when
- Conditions involve ranges - Complex logical expressions are neededUse switch when
- Comparing a single variable - Values are fixed and knownCheck Your Understanding
Question 1 of 5Which statement is used to execute code when a condition is true?
Age Checker
Write a program that checks whether a person is a child, adult, or senior based on age....
Grade Calculator
Create a grading system using else if....
Day Finder
Use switch to print the day of the week based on a number (1–7)....
Login Validation
Check if a user is logged in and has access using logical operators....
Refactor Practice
Convert an else if ladder into a switch statement where possible....