JavaScript Loops and Arrays
A clear teen tutorial on JavaScript loops and arrays: store lists of values, read them by index, and process every item with for loops, for...of and array methods like push and forEach, with runnable code and a quiz.
Key takeaways
- An array stores an ordered list of values inside square brackets
- Array items are read by index, starting at 0
- A for loop repeats code a set number of times using a counter
- for...of loops over each item in an array directly
- Methods like push, length and forEach let you build and process arrays
Why loops and arrays go together
Imagine you have the scores of 30 students. You could make 30 separate variables β score1, score2, ... β but that's a nightmare. Instead, JavaScript gives you an array: a single variable that holds an ordered list of values. And once you have a list, you'll want to do something with every item: add them up, print them, find the biggest. That's where loops come in. Arrays store the data; loops process it. They're a natural pair, which is why we learn them together.
This lesson assumes you know variables and basic syntax β if not, read Introduction to JavaScript first. We'll build up from a simple list to a working program that loops over it.
Creating an array
You write an array with square brackets, separating items with commas:
const scores = [85, 92, 78, 64, 100];
const names = ["Ava", "Ben", "Cara"];
const empty = [];
Each item sits at a numbered position called its index, and indexes start at 0, not 1:
const names = ["Ava", "Ben", "Cara"];
console.log(names[0]); // "Ava"
console.log(names[1]); // "Ben"
console.log(names[2]); // "Cara"
So names[0] is the first item. This trips up beginners constantly, so remember: first item = index 0.
How many items? The length property
Every array knows how long it is via .length:
const scores = [85, 92, 78];
console.log(scores.length); // 3
Because the last index is always one less than the length, the final item is scores[scores.length - 1].
Changing arrays
Arrays aren't frozen β you can add, change and remove items, even on a const array (the variable can't be reassigned, but its contents can change):
const fruit = ["apple"];
fruit.push("banana"); // add to the end β ["apple", "banana"]
fruit.push("cherry"); // β ["apple", "banana", "cherry"]
fruit[0] = "apricot"; // change the first item
fruit.pop(); // remove the last item β ["apricot", "banana"]
push is the one you'll use most β it adds an item to the end of the list.
The classic for loop
A for loop repeats a block of code a set number of times. It has three parts inside the parentheses:
for (let i = 0; i < 5; i++) {
console.log(i); // prints 0, 1, 2, 3, 4
}
Reading it left to right:
let i = 0β start a counter at 0 (the setup, runs once).i < 5β keep going while this is true (the condition, checked each time).i++β add 1 toiafter each pass (the update).
So it runs with i equal to 0, 1, 2, 3, 4, then stops because 5 < 5 is false. That's five times β perfect for stepping through an array's indexes.
Looping over an array with for
Combine the counter with .length to visit every item:
const scores = [85, 92, 78, 64];
for (let i = 0; i < scores.length; i++) {
console.log("Score " + i + " is " + scores[i]);
}
Because i goes from 0 up to scores.length - 1, scores[i] touches every item exactly once. Using scores.length (not a hard-coded number) means the loop still works if you add or remove scores later.
The cleaner for...of loop
When you only want the values and don't need the index, for...of is shorter and clearer:
const names = ["Ava", "Ben", "Cara"];
for (const name of names) {
console.log("Hello, " + name + "!");
}
Here name becomes each item in turn β no i, no [index], no off-by-one mistakes. Use for...of when you just want to visit every value, and a classic for when you need the position number.
forEach: a method that loops for you
Arrays also have a built-in forEach method that runs a function on every item:
const scores = [85, 92, 78];
scores.forEach(function (score) {
console.log("Score: " + score);
});
It does the looping internally and hands you each item. It's a matter of taste whether you prefer for...of or forEach β both visit every element.
A complete worked example
Let's combine arrays and loops into a small program that reports on a list of test scores. You can run this in your browser's console (press F12, go to the Console tab) or in any JavaScript playground.
const scores = [85, 92, 78, 64, 100, 73];
let total = 0;
let highest = scores[0];
// Loop once through the whole array
for (let i = 0; i < scores.length; i++) {
total = total + scores[i]; // add this score to the running total
if (scores[i] > highest) {
highest = scores[i]; // remember a new record if it's bigger
}
}
const average = total / scores.length;
console.log("Number of scores: " + scores.length);
console.log("Total: " + total);
console.log("Average: " + average);
console.log("Highest: " + highest);
What it does, step by step:
- It starts with
totalat 0 and assumes the first score is thehighest. - The loop visits each score once. It adds the score to
total, and if the score beats the current record, it updateshighest. - After the loop, it divides the total by
scores.lengthto get the average.
Running it prints the count, total, average and highest. With six scores the average is (85+92+78+64+100+73)/6 = 82. Change the numbers in the array and the program adapts automatically β that's the power of combining arrays with loops.
Try it yourself
- Count the passes. Add a counter that increases by 1 every time a score is 70 or above, then print how many students passed.
- Find the lowest. Copy the
highestlogic but flip the comparison to track the lowest score instead. - Build a list. Start with an empty array, then use a
forloop andpushto add the numbers 1 to 10 into it, and log the result.
Challenge: Make a "shopping list" program. Start with an array of three items, use a for...of loop to print each one as a numbered line (use a separate counter for the number), then push two more items and re-print the list. For an extra step, use array methods to count how many items contain the letter "a". When you're ready to put a list like this on a real page, see JavaScript and the DOM.
Quick quiz
Test yourself and earn XP
What is the index of the FIRST item in an array?
Array indexes start at 0, so the first item is array[0].
What does scores.length give you?
The length property returns how many items the array has.
How many times does `for (let i = 0; i < 3; i++)` run?
It runs for i = 0, 1, 2 β three times β and stops when i reaches 3 because the condition i < 3 becomes false.
What does array.push('a') do?
push adds a new item onto the end of the array.
Which loop reads each item of an array without using an index?
for (const item of array) gives you each value directly, no index needed.
FAQ
A classic for loop uses a counter (i) and is best when you need the index or want to count a specific number of times. for...of gives you each item directly and is cleaner when you just want to visit every value in an array.
Yes. JavaScript arrays can mix numbers, strings, booleans and even other arrays. In practice it's usually clearer to keep one kind of value per array, like all numbers or all names.
Keep exploring
More in Coding