JavaScriptLesson 7 of 18

JavaScript Arrays

An array is a list of values stored under one name. Each item has a position called an index, and the first item sits at index 0, not 1. Arrays hold anything: names, numbers, prices, or even objects. They are the main way JavaScript keeps groups of data together.

An array is a list of values stored under one name. Each item has a position called an index, and the first item sits at index 0, not 1. Arrays hold anything: names, numbers, prices, or even objects. They are the main way JavaScript keeps groups of data together.

Create an array with square brackets and separate the items with commas. The length property tells you how many items it holds, and it counts from one. The last item sits at length minus 1, because the indexes count from zero. That mismatch is where beginners stumble.

Arrays come with methods that change them in place. push adds an item to the end, pop removes the last one, and shift and unshift do the same at the front. Methods like slice and concat return new arrays and leave the original untouched. Knowing which is which matters, because surprising mutation is a common source of bugs.

Adding and removing items

push appends a value and pop removes the last value and returns it. A shopping cart is the classic use: push when the user adds a product, pop when they undo the last one.

JS
const cart = [];
cart.push("apple");
cart.push("bread");
cart.pop(); // removes "bread"

Reading arrays

Square brackets with an index read one item, and the length property works in loops and checks. Reading an index that does not exist does not throw an error; it quietly gives you undefined, which is worth knowing when you debug.

JS
const colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors[3]); // undefined, not an error

Syntax

JS
const fruits = ["apple", "banana", "cherry"];
fruits.push("date");
console.log(fruits.length); // 4
console.log(fruits[1]);     // "banana"

Array Length Is Not Last Index

Length counts from 1, indexes from 0 — last is length-1. arr[arr.length] is undefined.

JS
arr[arr.length-1] // last

Good to know

  • The first item sits at index 0; the last sits at length - 1.
  • push and pop change the end of the array in place.
  • Reading a missing index gives undefined, not an error.
  • slice and concat return new arrays; push, pop, shift mutate.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground