Chapter 4 - Control Structures in JavaScript
Chapter 4 - Control Structures in JavaScript
By Ahmed Thaer
Now that we can create variables, do math, and compare things, the next step is making our
programs react to different situations. Control structures let us decide what happens and
when. In JavaScript, the two most important kinds are conditional statements (like if) and
loops (like for and while).
The if statement is how we make choices in our code. It checks a condition—if it’s true, the
code inside runs. If it’s false, it skips that part.
Example:
javascript
CopyEdit
let age = 20;
if (age >= 18) {
console.log('You are an adult!');
}
if...else
If you want to do one thing if a condition is true, and something else if it’s false, use else.
javascript
CopyEdit
let isRaining = false;
if (isRaining) {
console.log('Take an umbrella!');
} else {
console.log('No need for an umbrella today.');
}
else if
javascript
CopyEdit
let score = 85;
When you have a lot of possible options for one variable, switch can make your code cleaner:
javascript
CopyEdit
let day = 'Saturday';
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('It’s the weekend!');
break;
case 'Monday':
console.log('Back to work!');
break;
default:
console.log('Just another day.');
}
Loops: Doing Things Repeatedly
Sometimes, you need to repeat actions—like printing all the numbers from 1 to 5. Loops make
this easy.
This is the most common loop when you know how many times you want to repeat.
javascript
CopyEdit
for (let i = 1; i <= 5; i++) {
console.log('Number: ' + i);
}
javascript
CopyEdit
let count = 1;
while (count <= 5) {
console.log('Count is: ' + count);
count++;
}
javascript
CopyEdit
let num = 1;
do {
console.log('Number is: ' + num);
num++;
} while (num <= 3);
Breaking and Continuing Loops
javascript
CopyEdit
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // Skip 3
if (i === 5) break; // Stop at 5
console.log(i);
}
// Output: 1, 2, 4
javascript
CopyEdit
let numbers = [2, 5, 8, 11];
Quick Practice
1. Write a program that prints “Fizz” for numbers divisible by 3 and “Buzz” for numbers
divisible by 5 (from 1 to 15).
2. Use an if statement to check if a user’s age is 21 or older, then print a message.
3. Loop through an array of your favorite foods and print each one.
Summary
Next up: Functions—how to group your code into reusable blocks that make your programs
cleaner and smarter.