JavaScript Loops and Arrays
After completing this topic
You will be able to create repetitive operations using for and while, and you will learn how to put, retrieve, and iterate data in arrays.
Repeating the Same Task
"Add numbers from 1 to 100," "Print each user in a list" - when you need to execute the same action multiple times, you use a loop.
// for loop - the most commonly used loop
// (start; condition; increment)
for (let i = 0; i < 5; i++) {
console.log(`${i}th iteration`);
}
// 0th iteration
// 1st iteration
// ...
// 4th iterationlet i = 0 - starting value, i < 5 - condition to continue, i++ - increment i by 1 each time the loop runs. These three parts control the number of repetitions.
// while loop - repeats based on a condition
let count = 0;
while (count < 3) {
console.log(`count is ${count}`);
count++;
}
// count is 0
// count is 1
// count is 2while continues as long as the condition is true. If you forget count++, the condition will always be true β leading to an infinite loop. When using loops, always check "when will this loop end?"
Arrays - Store Multiple Values in Order
If a variable can only hold one value, you would need 100 variables to store the names of 100 users. An array stores multiple values in a single variable in order.
const fruits = ["apple", "banana", "grape"];
// Access by index (starts at 0!)
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "grape"
console.log(fruits.length); // 3
// Add and remove
fruits.push("strawberry"); // Add to the end β ["apple", "banana", "grape", "strawberry"]
fruits.pop(); // Remove from the end β ["apple", "banana", "grape"]Note that the index starts at 0. In a 3-element array, the last index is 2. This is a common rule in almost all programming languages.
Array + Loop = Data Processing
By combining arrays and loops, you can process data one by one.
const scores = [85, 92, 78, 96, 88];
// Iterate with a for loop
let total = 0;
for (let i = 0; i < scores.length; i++) {
total += scores[i];
}
console.log(`Average: ${total / scores.length}`); // Average: 87.8
// for...of - a cleaner way to iterate
for (const score of scores) {
if (score >= 90) {
console.log(`${score} - Grade A`);
}
}
// 92 - Grade A
// 96 - Grade AUse for...of when you don't need the index; it's cleaner. It directly shows the meaning of "take out each element of the array" in the code.
// Array methods more commonly used in practice
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]map returns a new array with each element transformed, and filter returns a new array with only the elements that match the condition. Because they make the intent clearer than writing loops directly, these methods are used more often in practice.