JavaScript Arrays
An array is an ordered list of values. It can hold any mix of data types: numbers, strings, booleans, objects, or even other arrays.
Creating an array
The most common way to create an array is with square brackets:
const fruits = ['apple', 'banana', 'mango'];
const mixed = [1, 'hello', true, null];
You may also see new Array() in older code, but the square bracket syntax is shorter and preferred:
// Rarely needed; prefer the literal syntax above
const numbers = new Array(1, 2, 3);
Accessing elements
Arrays are zero-indexed, meaning the first element is at position 0.
const fruits = ['apple', 'banana', 'mango'];
console.log(fruits[0]); // 'apple'
console.log(fruits[1]); // 'banana'
console.log(fruits[2]); // 'mango'
The .at() method lets you access elements from the end using negative numbers:
console.log(fruits.at(-1)); // 'mango' (last element)
console.log(fruits.at(-2)); // 'banana' (second to last)
Updating elements
You can change any element by assigning to its index:
const fruits = ['apple', 'banana', 'mango'];
fruits[1] = 'grape';
console.log(fruits); // ['apple', 'grape', 'mango']
const and arrays
Declaring an array with const means you cannot reassign the variable to a different array. But you can still change the contents:
const colours = ['red', 'green'];
colours.push('blue'); // allowed
colours[0] = 'purple'; // allowed
// colours = ['new', 'array']; // Error: cannot reassign a const
Checking the length
The .length property returns the number of elements:
const students = ['Anna', 'Joe', 'Mira', 'Pete'];
console.log(students.length); // 4
Copying an array
Use the spread operator to create a shallow copy:
const original = ['a', 'b', 'c'];
const copy = [...original];
copy.push('d');
console.log(original); // ['a', 'b', 'c'] (unchanged)
console.log(copy); // ['a', 'b', 'c', 'd']
This is safer than assigning directly (const copy = original) because that would give you a reference to the same array, not a new one.
Nested arrays
Arrays can contain other arrays. Access nested values with multiple bracket notations:
const grid = [[1, 2], [3, 4], [5, 6]];
console.log(grid[1]); // [3, 4]
console.log(grid[1][0]); // 3
Converting to JSON
When sending data to an API or logging for debugging, JSON.stringify() turns an array into a JSON string:
const cart = [
{ id: 1, name: 'Book', price: 12 },
{ id: 2, name: 'Pen', price: 2 },
];
console.log(JSON.stringify(cart));
// '[{"id":1,"name":"Book","price":12},{"id":2,"name":"Pen","price":2}]'
What to read next
- Array Methods : push, pop, find, includes, flat, and more
- map() : transform every element into something new
- filter() : keep only the elements that pass a test
- reduce() : combine all elements into a single value