Control statements are used to control the flow of execution of a program based on certain conditions.
- Decision-making — Programs can choose different actions based on input or situations (e.g., if a user is logged in, show the dashboard).
- Control program flow — They determine which block of code should execute.
- Handle different situations — They allow programs to respond differently depending on the conditions.
Conditional Statements
Very often, when writing code, you want to perform different actions based on different decisions. You can use conditional statements to achieve this.
1️⃣ If statement
The if statement executes a block of code only if a specified condition is true.
// Syntax
if (condition) {
// Code to be executed if condition is true
}
// Example
if (time < 10) {
document.write("<b>Good morning</b>");
}
2️⃣ If...else statement
The if...else statement executes one block of code if the condition is true and another block if the condition is false.
// Syntax
if (condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}
// Example
if (time < 10) {
document.write("Good morning!");
} else {
document.write("Good day!");
}
3️⃣ Switch statement
The switch statement is used to select and execute one block of code from multiple possible options based on an expression.
// Syntax
switch (expression) {
case label1:
// Execute code block 1
break;
case label2:
// Execute code block 2
break;
default:
// Code to execute if no case matches
}
Example:
switch (theDay) {
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
Note
casespecifies a possible value to match.breakterminates the switch statement and prevents execution from continuing into the next case.defaultexecutes when none of the cases match.
Comments
Join the discussionNo comments yet. Be the first to comment.
Decode Javascript
Explore JavaScript one concept at a time, from the fundamentals to advanced topics. Learn through clear explanations, practical examples, and code as we uncover how JavaScript works and use it to build for the web.
