edubun
English
1 / 13

9 / 12 · Intro

Arrays in JavaScript

An array keeps many values in order under one name. In ["red", "green", "blue"], "red" sits at index 0 and the length is 3.

Jump to the 11 practice questions

You will learn

  • Keep values in order in an array and reach them by index
  • Loop over an array and see when two names share one array

Before this: Loops: for and while

1Explain

A list in one variable

Each value in an array is an element. Elements are numbered by index, starting at 0, exactly as characters in a string are. So the first element is fruits[0] and the last is fruits[fruits.length - 1]. Asking for an index that does not exist, such as fruits[10], does not cause an error; it gives undefined. An array can hold any kind of value, and the elements do not even have to be the same type, though in practice they usually are.

const fruits = ["apple", "banana", "cherry"];
console.log(fruits.length);   // 3
console.log(fruits[0]);       // apple
console.log(fruits[2]);       // cherry
Output
3
apple
cherry

2Explore

Pick an index

Indexes run from 0 to length - 1. Outside that range JavaScript gives undefined instead of an error.

index
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);
Output
apple

3Problem

The last element

What does this print?
const a = ["x", "y", "z"];
console.log(a[a.length - 1]);

Hint

length is 3, so the last index is 2.

Solution

Answer: z

length - 1 is 2, the last index.

4Explain

Changing an array

Unlike strings, arrays can be changed in place. Assign to an index to replace an element: fruits[1] = "blueberry". The method push adds an element to the end and pop removes the last one and gives it back. unshift and shift do the same at the start. This works even when the array was declared with const. const only stops the name from pointing to a different array; it does not freeze the contents.

The array is drawn as a row of boxes. push adds a box at the end, pop takes the last one off and hands it back.

  1. const list = ["milk", "eggs"];
  2. list.push("bread");
  3. console.log(list.length); // 3
  4. const last = list.pop();
  5. console.log(last); // bread
  6. console.log(list.join(", ")); // milk, eggs
Variables
Output
3
bread
milk, eggs

5Problem

pop and length

What does this print?

const a = [5, 6, 7];
const x = a.pop();
console.log(x, a.length);

Hint

pop returns the element it removes.

Solution

Answer: 7 2

pop removes and returns the last element, 7, leaving 2 elements.

6Explain

Looping over an array

Arrays and loops belong together. A for loop with an index from 0 up to, but not including, the length visits every element. The for...of loop is shorter when you only need the values, not their positions:

First i walks the indexes 0 to 3, then for...of hands over each value in turn.

  1. const scores = [70, 85, 90, 55];
  2. for (let i = 0; i < scores.length; i++) {
  3. console.log(i, scores[i]);
  4. }
  5. let total = 0;
  6. for (const s of scores) {
  7. total += s;
  8. }
  9. console.log(total / scores.length); // 75
Variables
Output
0 70
1 85
2 90
3 55
75

7Problem

Add the values

What does this print?

const a = [3, 4, 5];
let t = 0;
for (const n of a) {
  t += n;
}
console.log(t);

Hint

for...of gives 3, then 4, then 5.

Solution

Answer: 12

3 + 4 + 5 = 12.

8Explain

Two names, one array

Numbers and strings are copied when you assign them to another variable, but arrays are not. After const a = [1, 2]; const b = a; both names point to the very same array, so b.push(3) also changes what you see through a: a.length is now 3. If you need a separate copy, write const b = [...a];, which spreads the elements of a into a brand new array.

A dashed outline means "the same array as above". [...a] makes a new array of its own.

  1. const a = [1, 2];
  2. const b = a;
  3. b.push(3);
  4. console.log(a);
  5. const c = [...a];
  6. c.push(4);
  7. console.log(a, c);
Variables
Output
[1,2,3]
[1,2,3] [1,2,3,4]

9Problem

An index that is not there

What does this print?

const a = ["red", "green"];
console.log(typeof a[5]);

Hint

Reading past the end does not stop the program.

Solution

Answer: undefined

Reading a missing index gives undefined, not an error, so its type is "undefined".

10Practice

First, last, length

Print the first element, then the last element (using length), then the length, one per line.

Expected output
apple
cherry
3
Your code
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]);
Hint

The last element is at fruits.length - 1, not fruits.length.

A solution
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);
console.log(fruits[fruits.length - 1]);
console.log(fruits.length);

11Practice

push and join

Add "kiwi" to the end of the array with push, then print apple, banana, cherry, kiwi.

Expected output
apple, banana, cherry, kiwi
Your code
const fruits = ["apple", "banana", "cherry"];
// Add "kiwi" to the end, then print
// the list joined with ", ".
console.log(fruits.join(" "));
Hint

push("kiwi") first, then join with a comma and a space: ", ".

A solution
const fruits = ["apple", "banana", "cherry"];
fruits.push("kiwi");
console.log(fruits.join(", "));

12Explain

Common mistakes

const list = ["milk", "eggs"];
list.push("bread");
list = ["rice"];
Error message
TypeError: Assignment to constant variable. (line 3)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. The line number shows where the program stopped. A SyntaxError stops it before any line runs.

A const array can change inside (push works), but the name cannot be pointed at a new array.

const names = ["Ana", "Ji"];
console.log(names[2].toUpperCase());
Error message
TypeError: Cannot read properties of undefined (reading 'toUpperCase') (line 2)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. The line number shows where the program stopped. A SyntaxError stops it before any line runs.

names[2] does not exist, so it is undefined, and undefined has no methods. Check the index first.

13

Summary

  • Arrays hold ordered values in [ ]; indexes start at 0.
  • The last element is arr[arr.length - 1].
  • push and pop add and remove at the end; const arrays can still change inside.
  • includes, indexOf and join answer common questions.
  • Loop with i from 0 while i < length, or use for...of for the values.

Next unitFunctions
Full text · The whole lesson as one text

A list in one variable

Suppose a program tracks the scores of a whole class. Thirty variables named score1, score2, score3 would be miserable to work with, and impossible to loop over. An array is a single value that holds an ordered list of other values. You write it with square brackets and commas:

const fruits = ["apple", "banana", "cherry"];
console.log(fruits.length);   // 3
console.log(fruits[0]);       // apple
console.log(fruits[2]);       // cherry

Each value in an array is an element. Elements are numbered by index, starting at 0, exactly as characters in a string are. So the first element is fruits[0] and the last is fruits[fruits.length - 1]. Asking for an index that does not exist, such as fruits[10], does not cause an error; it gives undefined. An array can hold any kind of value, and the elements do not even have to be the same type, though in practice they usually are.

Changing an array

Unlike strings, arrays can be changed in place. Assign to an index to replace an element: fruits[1] = "blueberry". The method push adds an element to the end and pop removes the last one and gives it back. unshift and shift do the same at the start. This works even when the array was declared with const. const only stops the name from pointing to a different array; it does not freeze the contents.

const list = ["milk", "eggs"];
list.push("bread");
console.log(list.length);        // 3
const last = list.pop();
console.log(last);               // bread
console.log(list.join(", "));    // milk, eggs

Two more methods answer questions. includes(x) gives true if x is in the array, and indexOf(x) gives its index, or -1 if it is missing. join(", ") glues all the elements into one string with the given separator between them, which is the easiest way to print a list neatly.

Looping over an array

Arrays and loops belong together. A for loop with an index from 0 up to, but not including, the length visits every element. The for...of loop is shorter when you only need the values, not their positions:

const scores = [70, 85, 90, 55];

for (let i = 0; i < scores.length; i++) {
  console.log(i, scores[i]);
}

let total = 0;
for (const s of scores) {
  total += s;
}
console.log(total / scores.length);   // 75

Notice the condition i < scores.length, with < and not <=. With four elements the indexes are 0 to 3, and using <= would read one step past the end. This off-by-one mistake is one of the most common bugs in all of programming.

Two names, one array

Numbers and strings are copied when you assign them to another variable, but arrays are not. After const a = [1, 2]; const b = a; both names point to the very same array, so b.push(3) also changes what you see through a: a.length is now 3. If you need a separate copy, write const b = [...a];, which spreads the elements of a into a brand new array. Objects, covered in the next unit, behave the same way.

The practice boxes on this site print arrays in a compact form, such as ["a","b"] or [1,2,3]. The console in a browser developer tool adds spaces and may show them differently. Use join when you want exact control over the output.

Worked example. Find the largest number in [4, 17, 9, 12] without Math.max. Start with let best = nums[0], loop over the rest, and whenever an element is bigger than best, store it in best. After the loop best is 17. The same shape, a variable that remembers the best so far, finds the longest word, the cheapest price or the earliest date.

Before changing an array, predict both the returned value and the contents left behind. These are different questions. Removing the last element gives you that element, while the array itself becomes shorter. Adding an element changes the contents seen through every variable that refers to the same array. Check the array after each operation rather than assuming a method leaves the original list untouched.

Key points
  • Arrays hold ordered values in [ ]; indexes start at 0.
  • The last element is arr[arr.length - 1].
  • push and pop add and remove at the end; const arrays can still change inside.
  • includes, indexOf and join answer common questions.
  • Loop with i from 0 while i < length, or use for...of for the values.

Practice questions from Arrays in JavaScript on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (2)
  • MDN Web Docs, JavaScript Guide (developer.mozilla.org/en-US/docs/Web/JavaScript/Guide, chapters Introduction, Grammar and types, Control flow, Loops and iteration, Functions, Expressions and operators, Numbers and strings, Indexed collections, Working with objects; checked 2026-10-17)
  • Ecma International, ECMA-262 ECMAScript 2026 Language Specification, 17th edition, June 2026 (tc39.es/ecma262 and ecma-international.org/publications-and-standards/standards/ecma-262, checked 2026-10-17).

Checked: 2026-10-17