Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Array methods – JavaScript

Length: 10 minutes

Details

You can use various methods to modify arrays. To use an array method, write the name of the variable containing the array, add a period, the method name, and a pair of parentheses. The general format looks like this:

arrayName.method();

Some methods take one or more values, like this:

arrayName.method(value);
arrayName.method(value, value);
arrayName.method(value, value, value);

Add item(s) to end

To add item(s) to the end of an array, use the push() method. Place one or more values inside the parentheses, like this:

let letters = ['a', 'b', 'c'];
letters.push('d');
// letters = ['a', 'b', 'c', 'd']
let letters = ['a', 'b', 'c'];
letters.push('d', 'e', 'f');
// letters = ['a', 'b', 'c', 'd', 'e', 'f']

Remove last item

To remove the last item from an array, use the pop() method.

let letters = ['a', 'b', 'c'];
letters.pop();
// letters = ['a', 'b']

Add item(s) to beginning

To add item(s) to the beginning of an array, use the unshift() method. Place one or more values inside the parentheses, like this:

let letters = ['a', 'b', 'c'];
letters.unshift('d');
// letters = ['d', 'a', 'b', 'c']
let letters = ['a', 'b', 'c'];
letters.unshift('d', 'e', 'f');
// letters = ['d', 'e', 'f', 'a', 'b', 'c']

Remove first item

To remove the first item from an array, use the shift() method.

let letters = ['a', 'b', 'c'];
letters.shift();
// letters = ['b', 'c']

Insert item at specific index

To insert an item at a specific index, use the splice() method. In this case, the splice() takes 3 arguments. The first argument is the index where you want to insert an item. The second argument must be 0. The last argument is the value you want to insert.

let letters = ['a', 'b', 'c'];
letters.splice(1, 0, 'd');
// letters = ['a', 'd', 'b', 'c']

Remove item(s) at specific index

To remove an item at a specific index, use the splice() method. In this case, the splice() takes 2 arguments. The first argument is the index where you want to insert an item. The second argument is the number of items you want to remove.

let letters = ['a', 'b', 'c'];
letters.(1, 1);
// letters = ['a', 'c']

Replace item(s)

To replace an item at a specific index, use the splice() method. In this case, the splice() takes 3 arguments. The first argument is the index where you want to insert an item. The second argument is the number of items you want to replace. The last argument is the value (or values) you want to insert.

let letters = ['a', 'b', 'c'];
letters.splice(1, 1, 'd');
// letters = ['a', 'd', 'c']

Demo

Exercises

Create the letters array like in the code snippets above in your browser console in a new tab. Then try the various array methods on it. You can refresh the page if you’d like to start from scratch for each method.

References

Array object on MDN

Back to: JavaScript Reference > JS Data Types