introduction
Welcome to Part 4 of the JavaScript for Beginners Series. In this part, we focus on controlling the flow of your code using switch statements and automating tasks using Loops.
1. The switch Statement
Use a switch statement when you have one value that you need to compare against multiple possible options. It is often cleaner than a long chain of if/else if statements.
- case: Defines a specific value to check against.
- break: Crucial! The break keyword stops the execution inside the switch block. If you forget it, the code will continue to run into the next case.
- default: This block runs if the value doesn't match any of the case options (like the else part).
Darija :
- switch: ملي كتكون عندك قيمة وحدة و باغي تقارنها مع بزاف ديال الإحتمالات.
- case: كتمثل كل إحتمال.
- default: كتنفذ إلا مكان حتى إحتمال صحيح.
- Important: متنساش break!!!
Code Example:
const userRole = "admin";
switch (userRole) {
case "admin":
console.log("Full access granted.");
break; // Don't forget this!
case "editor":
console.log("Can edit content.");
break;
case "viewer":
console.log("View-only access.");
break;
default:
console.log("Unknown role.");
}
2. Loops: Automating Repetition
Why write the same code 100 times when you can write it once and tell the computer to repeat it? Loops are a fundamental concept for automating repetitive tasks.
The for Loop
This is the most common loop in JavaScript. Use it when you know exactly how many times you want to repeat an action. It is structured in three parts:
- Initialization: A counter variable is created (runs once).
- Condition: The loop continues as long as this is true.
- Increment: Updates the counter after each repetition.
- Darija: استعملها ملي كتكون عارف شحال من مرة باغي تعاود واحد العملية. الأجزاء ديالها هي: البدء، الشرط، والزيادة.
for (let i = 0; i < 5; i++) {
console.log("The current number is " + i);
}
The while Loop
Use the while loop when you want the loop to continue as long as a condition is true, but you don't necessarily know how many times it will run.
- Warning: If the condition never becomes false, you will create an infinite loop that crashes your program.
- Darija: استعمل while ملي كتبغي العملية تبقى كتعاود مادام واحد الشرط صحيح. رد البال باش متصاوبش حلقة لانهائية.
let i = 0;
while (i < 5) {
console.log("The number is " + i);
i++;
}
The do...while Loop
Similar to the while loop, but with one key difference: the code block is executed at least once because the condition is checked after the first run.
- Darija: بحال while ولكن الكود لي وسطها كيتنفذ على الأقل مرة وحدة عاد كيتم إختبار الشرط.
let num = 5;
do {
console.log(num); // This will run once, printing 5
} while (num < 3); // Condition is false, so it stops.
Looping over Arrays (for...of)
The for...of loop is the modern, clean way to iterate over the elements of an array.
- Darija: هي أحسن وأسهل طريقة باش دوز على العناصر ديال واحد Array.
const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
