JavaScript Arrays: Create, Access, Update and Loop
Learn JavaScript arrays from scratch: create lists, read and change items by index, use length, loop over them, and work with nested arrays and objects.
What you will learn
Until now, a variable held one value. But real programs deal with lists: ten student names, fifty products in a shop, hundreds of messages in a chat. You cannot create a hundred separate variables. JavaScript solves this with the array. In this lesson you will learn how to create an array, read and change its items using an index, use length, loop over every item, and work with arrays inside arrays and arrays of objects.
What is an array?
An array is an ordered list of values stored in a single variable.
Think of an egg tray: one tray, many numbered holes. Each hole holds one item, and you can find any item by its position.
const fruits = ["apple", "banana", "mango"];
console.log(fruits); // ["apple", "banana", "mango"]
Arrays are written with square brackets [ ], and the items are separated by commas.
Arrays can hold any type of value, even a mix:
const numbers = [10, 20, 30];
const flags = [true, false, true];
const mixed = ["Riya", 20, true, null];
const empty = [];
In practice, most arrays hold values of one kind (all names, all prices), because that is easier to work with.
Creating arrays
1. Array literal (the normal way)
const colors = ["red", "green", "blue"];
2. Array.of() and Array.from()
console.log(Array.of(7)); // [7]
console.log(Array.from("abc")); // ["a", "b", "c"] (turns text into an array)
// Create a list of 1 to 5
console.log(Array.from({ length: 5 }, (_, i) => i + 1)); // [1, 2, 3, 4, 5]
The last line is a handy trick: it creates 5 slots and fills each one using the function. _ is a name for a value we do not need, and i is the position.
3. new Array() (avoid it)
const a = new Array(3); // 3 EMPTY slots, not [3]!
const b = new Array(1, 2, 3); // [1, 2, 3]
console.log(a.length); // 3
new Array(3) makes an array with 3 empty slots, and new Array(1, 2, 3) makes a list. That inconsistency causes bugs, so use [ ] instead.
Checking if something is an array
typeof does not help, because an array is a kind of object:
console.log(typeof [1, 2, 3]); // "object"
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray("hello")); // false
Use Array.isArray().
Indexing: reading items
Every item has a position called an index, and counting starts at 0.
index: 0 1 2
"apple" "banana" "mango"
const fruits = ["apple", "banana", "mango"];
console.log(fruits[0]); // "apple" (the FIRST item)
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "mango"
console.log(fruits[3]); // undefined (there is no item at index 3)
length and the last item
length tells you how many items the array holds. The last index is always length - 1.
const fruits = ["apple", "banana", "mango"];
console.log(fruits.length); // 3
console.log(fruits[fruits.length - 1]); // "mango" (last item)
console.log(fruits.at(-1)); // "mango" (easier!)
console.log(fruits.at(-2)); // "banana" (second from the end)
at() accepts negative numbers, which count from the end. Normal brackets fruits[-1] do not work (they give undefined).
Updating items
Assign a new value to a position:
const fruits = ["apple", "banana", "mango"];
fruits[1] = "grapes";
console.log(fruits); // ["apple", "grapes", "mango"]
const arrays can still change
const stops you from re-assigning the variable, but the contents of the array can change:
const fruits = ["apple"];
fruits.push("banana"); // allowed
fruits[0] = "mango"; // allowed
console.log(fruits); // ["mango", "banana"]
fruits = ["new array"]; // TypeError: Assignment to constant variable
Use const for arrays almost always. You only need let if you want the variable to point to a completely new array.
Adding at a new position
const fruits = ["apple", "banana"];
fruits[2] = "mango"; // adds at the end
console.log(fruits); // ["apple", "banana", "mango"]
If you skip positions, you create holes (empty slots), which cause confusing bugs:
const list = ["a", "b"];
list[5] = "f";
console.log(list.length); // 6
console.log(list[3]); // undefined (an empty hole)
To add items to the end, use push() (you will see it below and in the next lesson).
The length property
const scores = [70, 85, 90];
console.log(scores.length); // 3
Check whether an array is empty:
const cart = [];
if (cart.length === 0) {
console.log("Your cart is empty");
}
Remember: an empty array [] is truthy, so if (cart) does not work for this check.
Looping over an array
1. The classic for loop (you need the index)
const fruits = ["apple", "banana", "mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}
Output:
0 apple
1 banana
2 mango
2. for...of (you only need the values)
const fruits = ["apple", "banana", "mango"];
for (const fruit of fruits) {
console.log(fruit);
}
This is the simplest and the one you will use most.
3. .forEach() (a method with a callback)
const fruits = ["apple", "banana", "mango"];
fruits.forEach((fruit, index) => {
console.log(`${index + 1}. ${fruit}`);
});
Output:
1. apple
2. banana
3. mango
forEach calls your function once for every item, giving it the item and its index. One limit: you cannot stop it early with break. Use for or for...of if you need to stop.
4. for...of with .entries() (value and index)
const fruits = ["apple", "banana", "mango"];
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}
Which loop should I use?
| Need | Use |
|---|---|
| Just the items | for...of |
Items and index, with break |
for loop, or for...of with .entries() |
| Simple “do this for every item” | forEach |
| Do not use | for...in (it gives string indexes) |
Printing and converting arrays
const fruits = ["apple", "banana", "mango"];
console.log(fruits); // shows the array
console.log(fruits.join(", ")); // "apple, banana, mango"
console.log("List: " + fruits); // "List: apple,banana,mango"
console.log(String(fruits)); // "apple,banana,mango"
Joining an array with + or printing it inside text calls String() on it, which separates items with commas without spaces. Use join() to choose your own separator.
Arrays are reference values
When you write const b = a; with an array, you do not make a copy. Both names point to the same array:
const a = [1, 2, 3];
const b = a;
b.push(4);
console.log(a); // [1, 2, 3, 4] (a changed too!)
console.log(a === b); // true (same array)
To make a real copy, use the spread syntax [...a] or .slice():
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
For the same reason, comparing two arrays with === checks if they are the same array, not if they have the same items:
console.log([1, 2, 3] === [1, 2, 3]); // false (two different arrays)
A later lesson on value vs reference explains this fully.
Nested arrays (2D arrays)
An array can contain other arrays. This is perfect for tables, grids and boards.
const marks = [
[70, 80, 90], // row 0: Riya
[60, 75, 85], // row 1: Karan
[88, 92, 79] // row 2: Neha
];
console.log(marks[1]); // [60, 75, 85]
console.log(marks[1][2]); // 85 (row 1, column 2)
Use two indexes: the first picks the row, the second picks the item inside it.
Loop through every cell with nested loops:
const marks = [
[70, 80, 90],
[60, 75, 85],
[88, 92, 79]
];
for (let row = 0; row < marks.length; row++) {
let total = 0;
for (let col = 0; col < marks[row].length; col++) {
total += marks[row][col];
}
console.log(`Student ${row + 1} total: ${total}`);
}
Output:
Student 1 total: 240
Student 2 total: 220
Student 3 total: 259
Arrays of objects
In real applications, you will mostly see arrays of objects, such as a list of users, products or posts. (Objects have their own lesson soon. For now, think of an object as a record with named fields.)
const students = [
{ name: "Riya", marks: 82 },
{ name: "Karan", marks: 67 },
{ name: "Neha", marks: 91 }
];
console.log(students[0]); // { name: "Riya", marks: 82 }
console.log(students[2].name); // "Neha"
console.log(students.length); // 3
for (const student of students) {
console.log(`${student.name} scored ${student.marks}`);
}
This shape, [{...}, {...}, {...}], is also the format of most data you get from servers (JSON).
A first look at array methods
Arrays come with many built-in methods. Here are the most common ones, to get a feeling. The next lessons explain each one properly.
const fruits = ["apple", "banana"];
fruits.push("mango"); // add to the end
console.log(fruits); // ["apple", "banana", "mango"]
fruits.pop(); // remove from the end
console.log(fruits); // ["apple", "banana"]
console.log(fruits.includes("apple")); // true (is it in the list?)
console.log(fruits.indexOf("banana")); // 1 (where is it?)
console.log(fruits.join(" + ")); // "apple + banana"
console.log(fruits.reverse()); // ["banana", "apple"]
Beware: push, pop and reverse change the original array. The next lesson shows which methods do that and which do not.
Real-life use cases
1. Shopping cart total
const prices = [250, 99, 1499, 75];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(`Total: ₹${total}`); // "Total: ₹1923"
2. Average, highest and lowest marks
const marks = [72, 85, 90, 64, 78];
let sum = 0;
let highest = marks[0];
let lowest = marks[0];
for (const mark of marks) {
sum += mark;
if (mark > highest) highest = mark;
if (mark < lowest) lowest = mark;
}
console.log("Average:", sum / marks.length); // 77.8
console.log("Highest:", highest); // 90
console.log("Lowest:", lowest); // 64
// A shortcut with Math and spread
console.log(Math.max(...marks), Math.min(...marks)); // 90 64
3. Remove duplicates
const tags = ["js", "html", "js", "css", "html", "js"];
const uniqueTags = [...new Set(tags)];
console.log(uniqueTags); // ["js", "html", "css"]
A Set stores each value only once. Spreading it back gives a clean array.
4. Count how many times each item appears
const votes = ["red", "blue", "red", "green", "red", "blue"];
const counts = {};
for (const vote of votes) {
counts[vote] = (counts[vote] || 0) + 1;
}
console.log(counts); // { red: 3, blue: 2, green: 1 }
5. A to-do list
const todos = ["Buy milk", "Study JavaScript"];
todos.push("Go for a walk");
todos.forEach((task, index) => {
console.log(`${index + 1}. ${task}`);
});
Output:
1. Buy milk
2. Study JavaScript
3. Go for a walk
6. A game board (2D array)
const board = [
["X", "O", "X"],
["O", "X", "O"],
[" ", " ", "X"]
];
for (const row of board) {
console.log(row.join(" | "));
}
Output:
X | O | X
O | X | O
| | X
7. First letters of names
const names = ["Riya Sharma", "Karan Mehta", "Neha Singh"];
const initials = [];
for (const fullName of names) {
const [first, last] = fullName.split(" ");
initials.push(first[0] + last[0]);
}
console.log(initials); // ["RS", "KM", "NS"]
const [first, last] = ... is array destructuring: it unpacks the items into two variables. You will learn it in its own lesson.
8. Generating a list of numbers
const oneToTen = Array.from({ length: 10 }, (_, i) => i + 1);
console.log(oneToTen); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Common mistakes
- Starting at index 1. The first item is
array[0]. - Using
array[array.length]for the last item. That is one past the end (undefined). Usearray[array.length - 1]orarray.at(-1). - Using
array[-1]. It does not work. Useat(-1). - Checking an array with
typeof. It says"object". UseArray.isArray(). - Thinking
const b = acopies the array. It does not. Use[...a]. - Comparing arrays with
===or==. They compare references, not contents. - Testing emptiness with
if (array). An empty array is truthy. Checkarray.length. - Using
for...inon arrays. It returns string indexes. Usefor...of. - Using
new Array(3). It creates empty slots, not[3]. - Leaving holes by assigning to a far-away index.
- Changing an array while looping over it. Items can get skipped. Loop over a copy, or build a new array.
- Forgetting that
constarrays can still change. - Printing with
+."List: " + arrayremoves the nice formatting. Usejoin()orconsole.log(array).
Practice
- Create an array of your 5 favourite movies. Print the first one, the last one, and how many there are.
- Change the second movie to another title and print the whole array.
- Create an array of numbers
[4, 8, 15, 16, 23, 42]and print only the even ones usingfor...of. - Calculate the sum and average of
[12, 45, 7, 89, 23]. - Find the largest number of
[12, 45, 7, 89, 23]with a loop (noMath.max). - Create
const a = [1, 2, 3]; const b = a; b.push(4);and print both. Then redo it withconst b = [...a]. Explain the difference. - Create a 3×3 array with the numbers 1 to 9. Print the middle number and the sum of the diagonal (
1 + 5 + 9). - Create an array of three book objects (
titleandprice). Print each title with its price, and the total price. - Use
Array.from({ length: 5 }, (_, i) => i * 2)to create[0, 2, 4, 6, 8]. Then change it to create[10, 20, 30, 40, 50]. - Challenge: given
["a", "b", "a", "c", "b", "a"], build an object that counts each letter, and print the letter that appears the most.
Recap
- An array is an ordered list of values in one variable, written with
[ ]. - Items are read by index, starting at 0.
lengthis the number of items, and the last index islength - 1.at(-1)gives the last item. - You can update an item with
array[index] = value. Aconstarray can still be changed, but the variable cannot be re-assigned. - Loop with
for,for...oforforEach. Avoidfor...infor arrays. - Arrays are reference values:
const b = ashares the same array. Copy with[...a]. - Use
Array.isArray()to check for an array, andarray.length === 0to check if it is empty. - Nested arrays make tables and boards (
matrix[row][col]), and arrays of objects are how most real data looks. - Next you will learn the array methods for adding, removing, copying, searching and joining items:
push,pop,shift,unshift,slice,splice,concat,includes,indexOfandjoin.