Array Methods
Add, remove and transform items with array methods.
Syntax
arr.push(item)
arr.join(', ')Arrays come with many useful methods:
push()— add to the end;pop()— remove from the end.unshift()— add to the start;shift()— remove from the start.join()— combine into a string.includes()— check if a value exists.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Add a new comment to the beginning of a comments array with unshift when showing newest-first.
- Remove the first item from a task queue with shift after it has been processed.
- Merge two arrays of product tags using concat to form a combined tag list for a search filter.
More examples
shift and unshift
Uses unshift to add a task to the front of a queue and shift to dequeue the first task.
const queue = ["task2", "task3"];
queue.unshift("task1"); // add to front
console.log(queue); // ["task1", "task2", "task3"]
const processed = queue.shift(); // remove from front
console.log(processed); // "task1"concat to merge arrays
Uses concat to join two paginated result arrays into a single list without mutating either original.
const page1 = ["Alice", "Bob"];
const page2 = ["Carol", "Dan"];
const all = page1.concat(page2);
console.log(all); // ["Alice", "Bob", "Carol", "Dan"]indexOf and includes
Uses includes to test membership and indexOf to find the position of a tag in an array.
const tags = ["javascript", "react", "css"];
console.log(tags.includes("react")); // true
console.log(tags.indexOf("css")); // 2
console.log(tags.indexOf("vue")); // -1
Discussion