Array methods
Arrays rarely stay the same: products are added to a cart, tasks are taken from a queue. Arrays have built-in methods for this. A method is a function that belongs to a value and is called with a dot: colors.push().
push and pop
push() adds an element to the end of an array, and pop() removes the last element and returns it:
const cart = ['bread', 'milk'];
cart.push('cheese');
console.log(cart.join(', ')); // bread, milk, cheeseconst cart = ['bread', 'milk', 'cheese'];
const last = cart.pop();
console.log(last); // cheese
console.log(cart.join(', ')); // bread, milkunshift and shift
The same actions at the start of an array are done by unshift() — add to the front — and shift() — remove the first element:
const queue = ['Anna', 'Oleg'];
queue.unshift('Ira');
const first = queue.shift();
console.log(first); // Ira
console.log(queue.join(', ')); // Anna, OlegThis is how a queue works: newcomers join the end with push(), and the first one is served with shift().
slice — a copy of a part
slice(start, end) returns a new array with the elements from index start up to, but not including, index end. The original array does not change:
const letters = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.slice(1, 3).join(', ')); // b, c
console.log(letters.slice(-2).join(', ')); // d, e
console.log(letters.length); // 5Without arguments, slice() copies the whole array.
splice — removing and inserting
splice(start, count) removes elements right from the array. After the count you can list elements that take the place of the removed ones:
const letters = ['a', 'b', 'c', 'd'];
letters.splice(1, 2, 'X');
console.log(letters.join(', ')); // a, X, dconcat and join
concat() joins arrays into a new one, and join() turns an array into a string:
const fruits = ['apple', 'pear'];
const berries = ['raspberry'];
const all = fruits.concat(berries);
console.log(all.join(' + ')); // apple + pear + raspberry| Method | What it does | Changes the array |
|---|---|---|
push() / pop() | adds / removes at the end | yes |
unshift() / shift() | adds / removes at the start | yes |
splice() | removes and inserts | yes |
slice() | copies a part | no |
concat() | joins arrays | no |
Common mistake
The names slice and splice look alike and are easy to mix up. slice() is safe — it only copies, while splice() cuts elements out of the original array:
const numbers = [1, 2, 3, 4];
numbers.splice(0, 2);
console.log(numbers.join(', ')); // 3, 4If you still need the original array, use slice().