0% found this document useful (0 votes)
3 views9 pages

Week 4 JS Note

This document covers loops and iteration in JavaScript, detailing various types such as for, while, do...while, for...of, and for...in loops, along with array methods like forEach, map, filter, and reduce. It explains the use cases for each loop type and provides practical examples and exercises to reinforce understanding. Additionally, it discusses loop control flow statements like return, break, and continue, along with best practices for using loops effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Week 4 JS Note

This document covers loops and iteration in JavaScript, detailing various types such as for, while, do...while, for...of, and for...in loops, along with array methods like forEach, map, filter, and reduce. It explains the use cases for each loop type and provides practical examples and exercises to reinforce understanding. Additionally, it discusses loop control flow statements like return, break, and continue, along with best practices for using loops effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

CWEEK 4: LOOPS & ITERATION IN JAVASCRIPT

Loops and iteration are fundamental concepts in JavaScript that


allow developers to execute a block of code multiple times
efficiently. JavaScript provides several types of loops, including
traditional loops (for, while, do...while), ES6+ loops (for...of,
for...in), and array/object iteration methods (forEach, map, filter,
reduce). Understanding when and how to use each of these loops
is essential for writing clean and efficient code.

1. Understanding Loops in JavaScript


1.1 The for Loop

The for loop is used when the number of iterations is known


beforehand. It consists of three parts:

 Initialization: Declares and initializes the loop variable.


 Condition: Defines the stopping criteria for the loop.
 Iteration Statement: Updates the loop variable after each
iteration.

for (initialization; condition; increment/decrement) {


// Code to execute in each loop iteration
}

Example: Printing numbers from 1 to 5


for (let i = 1; i <= 5; i++) {
console.log(i);
}

Use Cases

 Counting numbers in a sequence


 Iterating through an array
 Running a loop for a specific number of times
1.2 The while Loop

The while loop is used when the number of iterations is not


known beforehand. The loop continues executing as long as the
condition evaluates to true.

while (condition) {
// Code to execute
}

Example: Printing numbers from 1 to 5


let i = 1;
while (i <= 5) {
console.log(i);
i++;
}

Use Cases

 Running a loop until a user enters valid input


 Handling unpredictable data
 Polling for data updates

1.3 The do...while Loop

The do...while loop ensures that the code executes at least


once, even if the condition is initially false.

do {
// Code to execute
} while (condition);

Example: Keep prompting until the user enters a number greater


than 0
let number;
do {
number = parseInt(prompt("Enter a number greater than 0:"));
} while (number <= 0);
console.log("You entered:", number);

Use Cases

 Ensuring code execution at least once


 Validating user input before checking conditions

1.4 The for...of Loop (ES6+)

The for...of loop is used to iterate over iterable objects such as


arrays, strings, Maps, and Sets.

for (let variable of iterable) {


// Code to execute
}

Example: Looping through an array of names


let names = ["Alice", "Bob", "Charlie"];
for (let name of names) {
console.log(name);
}

Use Cases

 Iterating through arrays and strings


 Avoiding index-based iteration (for loop)

1.5 The for...in Loop (ES6+)

The for...in loop is used to iterate over the keys (properties) of


an object.
for (let key in object) {
// Code to execute
}
Example: Iterating through an object
let student = {
name: "John",
age: 20,
grade: "A"
};

for (let key in student) {


console.log(`${key}: ${student[key]}`);
}

Use Cases

 Iterating through objects and their properties


 Reading object key-value pairs

2. Iterating Over Arrays


2.1 The forEach() Method

Executes a function for each array element without returning a


new array.

Example: Printing each item in an array

let colors = ["Red", "Blue", "Green"];


colors.forEach(color => console.log(color));

Use Cases

 Logging array elements


 Performing side effects (e.g., updating UI, fetching data)
2.2 The map() Method

Creates a new array by applying a function to each element.

Example: Doubling each number in an array

let numbers = [1, 2, 3, 4];


let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

Use Cases

 Transforming data without modifying the original array


 Creating a new array with computed values

2.3 The filter() Method

Creates a new array containing elements that meet a condition.

Example: Getting only even numbers

let numbers = [1, 2, 3, 4, 5, 6];


let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

Use Cases

 Filtering data from an API response


 Removing unwanted elements

2.4 The reduce() Method

Reduces an array to a single value (e.g., sum, product).

Example: Summing all numbers in an array


let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

Use Cases

 Calculating totals (sum, product, average)


 Aggregating data

3. Iterating Over Objects

JavaScript provides built-in methods to iterate over objects:

3.1 Object.keys() – Retrieve object keys


let user = { name: "Alice", age: 25, city: "Lagos" };
console.log(Object.keys(user)); // ["name", "age", "city"]

3.2 Object.values() – Retrieve object values


console.log(Object.values(user)); // ["Alice", 25, "Lagos"]

3.3 Object.entries() – Retrieve key-value pairs


console.log(Object.entries(user));
// [["name", "Alice"], ["age", 25], ["city", "Lagos"]]

4. LOOP CONTROL FLOW STATEMENTS


The term “Control Flow” encompasses all constructs in
programming language that affects the order in which
instructions are executed.
Examples
1. Return
Purpose: Stops the execution of a function and sends a value
back to where the function is called.
Use Case: When you want to output a value from a function.
function add(a, b) {
return a + b; // Returns the sum of a and b
}
let result = add(5, 3)
*Note: If you don’t include the return keyword, the function will
return “undefined” by default.
2. break:
Purpose: Exists a loop or a “switch” statement immediately
Use Case: When you need to stop a loop based on a condition.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // Exists the loop when I is 3
}
Console.log(i)
}
// Output: 1, 2
3. Continue:
Purpose: Skips the rest of the current loop iteration and moves
to the next one.
Use Case: When you want to skip a certain iteration without
breaking the loop.
for (let i = 1; i<=5; i++) {
if (i === 3) {
continue; // Skip the iteration when I is 3
}
Console.log(i)
}
Output: 1, 2, 4, 5
Key Differences.
i) return: Ends a function and optionally returns a valuel
ii) break: Exits a loop or switch completely.
iii) continue: Skips the current iteration and moves forward.

4. Practical Exercises
Exercise 1: Print numbers from 1 to 10

👉 Use a for loop.

Exercise 2: Find even numbers in an array

👉 Use filter() to return only even numbers.

Exercise 3: Sum all numbers in an array

👉 Use reduce() to calculate the sum.

Exercise 4: Print a pyramid pattern

👉 Use nested loops to print:

Exercise 5: Iterate over an object and log key-value pairs

👉 Given an object:

let person = { name: "John", age: 30, job: "Developer" };


Use for...in or Object.entries() to print its properties.
5. Best Practices

✔ Use forEach() for simple iterations, map() for transformations.


✔ Avoid infinite loops (while (true) {} without break).
✔ Use let inside loops for proper scoping.
✔ Choose the right loop for the task.

You might also like