Intro to Array
Arrays are lists of data in JavaScript. Learn how to create arrays, access items by index, check length, and modify values.
Arrays are lists of data in JavaScript. Learn how to create arrays, access items by index, check length, and modify values.
An array is an ordered list. It lets you store multiple values in a single variable and access them by position.
Use square brackets:
const colors = ["red", "green", "blue"];const numbers = [1, 2, 3, 4, 5];const mixed = ["hello", 42, true, null];Arrays can hold any type of value, including other arrays.
Items are numbered starting at zero:
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // 'apple'fruits[1]; // 'banana'fruits[2]; // 'cherry'fruits[3]; // undefined — past the endThe last item is always at index array.length - 1.
fruits.length; // 3You can update an item directly by index:
fruits[1] = "mango";// ['apple', 'mango', 'cherry']When you assign an array to a variable, both variables 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 tooIf you want an independent copy, use slice() or the spread operator:
const b = [...a]; // independent copyOnce you’re comfortable with arrays, the real power comes from array methods: forEach, map, filter, find, and reduce. Each one solves a specific kind of problem without writing a loop manually.