Chapter 3 — JS Conditionals & Loops
📚 Chapter Overview
JavaScript logic allows your website to react to different scenarios. In this chapter, you will learn how to use if-else statements for decision-making and for loops to handle repetitive data.
Learning Objectives:
- Master
if,else if, andelsebranching. - Use
forloops to iterate over arrays. - Understand Truthy and Falsy values.
3.1 If-Else Decisions
Part 1 — Definition
Conditional statements check a condition. If it is true, the code inside the block executes. If false, it moves to the else block. You can chain multiple checks using else if.
Part 2 — Syntax
if (condition) {
// True code
} else if (anotherCondition) {
// Alternative code
} else {
// Default code
}
Part 3 — Example
Problem: Check if a user is old enough to enter a site.
script.js
let age = 17;
if (age >= 18) {
console.log("Access Granted");
} else {
console.log("Access Denied");
}
Part 4 — Video
Video: Coming Soon
3.2 Repetition with For Loops
Part 1 — Definition
A for loop allows you to run a block of code multiple times. It is commonly used to process items in a list (Array) or to repeat a mathematical calculation.
Part 2 — Syntax
for (let i = 0; i < 5; i++) {
console.log(i);
}
Part 3 — Example
Problem: Print each student's name from a list.
script.js
let students = ["Ali", "Sara", "John"];
for (let i = 0; i < students.length; i++) {
console.log(`Student ${i+1}: ${students[i]}`);
}
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Create a "FizzBuzz" program that uses both logic and loops.
Requirements
- Loop from 1 to 20.
- If the number is divisible by 3, log "Fizz".
- If divisible by 5, log "Buzz".
- If divisible by both, log "FizzBuzz".
Step-by-Step Process
- Use a
forloop from 1 to 20. - Use the modulus operator
%to check for divisibility. - Use an
if-else if-elseladder.
Expected Deliverables
fizzbuzz.jssource code.