Control flow allows you to conditionally run blocks of code based on a set of rules. By using control flow statements like if...else and switch, you can write functions that make decisions based on certain conditions being met. In this tutorial, we'll explore the basic control flow statements, including examples and best practices for each.
Key Takeaways
- Use if statements for simple conditions.
- if...else handles binary decisions.
- else...if allows for multiple conditions.
- switch is optimal for multiple discrete values.
- break prevents unnecessary execution in switch statements.
if
let x = 0;
if(x === 0) {
console.log("x is zero!");
}
//logs "x is zero!"
This is the most basic control flow statement. It allows you to run a block of code if a certain condition is met. In JavaScript, it's best to use strict equality === to avoid type coercion issues.
if...else
let x = 1;
if(x === 0) {
console.log("x is zero!");
} else {
console.log("x is not zero!");
}
//logs "x is not zero!"
In an if...else statement, the code block in the else clause gets executed only if the if condition is not met. This structure provides a fallback execution path.
else...if
let x = 2;
if(x === 0) {
console.log("x is zero!");
} else if(x === 1) {
console.log("x is one!");
} else {
console.log("x is neither zero nor one!");
}
//logs "x is neither zero nor one!"
The else...if clause extends the if...else decision-making process to handle multiple conditions. Always include a final else clause as a "catch-all" to handle unexpected values.
switch
let a = 0;
switch (a + 1) {
case 0:
console.log("hello");
break;
case 1:
case 2:
console.log("goodbye");
break;
case 3:
console.log("adios");
break;
default:
console.log("no cases match");
}
//logs "goodbye"
The switch statement evaluates an expression and executes the block of code that matches a case. It's an efficient way to handle multiple discrete values and comes in handy to avoid deep if...else nesting.
The break keyword
Using the break keyword is critical in switch cases to stop further execution once a matching case has been executed. Without break, execution will "fall through" to subsequent cases.
The default case
Adding a default case in a switch statement provides a fallback for when none of the case conditions are met. It’s good practice to prevent undefined behavior.
switch vs if...else
Switch statements can save you a lot of repetition when you have multiple conditions to check against a single variable. Rewriting a switch statement as if...else could make your code longer and less readable:
if(a + 1 === 0) {
console.log("hello");
} else if(a + 1 === 1 || a + 1 === 2) {
console.log("goodbye");
} else if(a + 1 === 3) {
console.log("adios");
} else {
console.log("no cases match");
}
While the end result is the same, you'll find switch statements easier to maintain and read in many scenarios.
FAQ
Is it better to use === instead of == in JavaScript?
Yes, using === is recommended to prevent type coercion, ensuring both type and value are matched.
What happens if I forget a break in a switch statement?
If you forget a break, execution will continue with the next case, potentially causing unintended behavior unless you explicitly want fall-through logic.
Are switch statements faster than if...else?
In some scenarios, switch statements can be faster than if...else due to optimized jump tables in underlying engine implementations, but this depends on the specific use case and JavaScript engine.
Can I use a function call as a case in a switch statement?
No, cases in a switch need to be constant values. However, you can call a function to evaluate a value that you then compare in the switch expression.
