JavaScript Array Methods
Array methods change or read the items in an array. Each method runs when a call names its array and its method.
Push and pop
Array methods change or read an array, and these two calls change this one. The popped value logs on its own line.
const fruits = ["Apple", "Pear"];
fruits.push("Plum");
console.log(fruits);
const last = fruits.pop();
console.log(last);
console.log(fruits);Join into a string
The join call reads the items and builds one string. The separator sits between each pair of items.
const fruits = ["Apple", "Pear", "Plum"];
const line = fruits.join(", ");
console.log(line);Concat two arrays
The concat call builds a new array from two arrays. All three arrays log below as evidence.
const a = ["Apple", "Pear"];
const b = ["Plum", "Kiwi"];
const all = a.concat(b);
console.log(all);
console.log(a);
console.log(b);Example
const fruits = ["Apple", "Pear"];
fruits.push("Plum");
console.log(fruits);
const last = fruits.pop();
console.log(last);
const line = fruits.join(" - ");
console.log(line);Key points
- push adds one or more items at the end of an array.
- pop removes the last item and returns it.
- join builds one string from the items and a separator.
- concat builds a new array and leaves both originals whole.
- shift removes the first item, and unshift adds items at the start.
- toString turns an array into a comma-separated string.
In this example, the fruits array starts with two items. The push call adds Plum at the end, and the log shows three items. The pop call removes Plum and stores it in last, and the next line logs it. The join call then builds one string from the two remaining items.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does the push method do to an array?