Arrays
Arrays store ordered lists of values in a single variable.
Syntax
let fruits = ['apple', 'banana'];An array is an ordered list of values. Write it with square brackets, separating items with commas.
Key points
- Items are accessed by index, starting at
0. array.lengthgives the number of items.- An array can hold mixed types.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Store a list of product IDs in the current shopping cart to send with a checkout request.
- Hold a collection of search results returned from an API before rendering them as a list.
- Keep an ordered queue of pending notifications to display one at a time.
More examples
Declare and access an array
Declares an array literal and accesses elements by zero-based index and the length property.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
console.log(fruits.length); // 3Mixed-type array
Shows that JavaScript arrays can hold values of different types in the same collection.
const record = [1, "Alice", true, null];
console.log(record[1]); // "Alice"
console.log(record[3]); // nullPush and pop elements
Uses push to add multiple items to the end of an array and pop to remove and return the last one.
const cart = ["book"];
cart.push("pen", "ruler");
console.log(cart); // ["book", "pen", "ruler"]
const removed = cart.pop();
console.log(removed); // "ruler"
Discussion