JavaScript array methods

This tutorial explains how to use the following array methods in JavaScript:

  • push() to append elements to the end of an array
  • pop() to remove the last element from an array
  • shift() to remove the first element from an array
  • unshift() to add an element to the beginning of an array
  • delete to change an element to undefined in an array
  • splice() to add or remove elements from an array
  • concat() to concatenate (join) two or more arrays together

Watch the video below and then scroll down to see the sample code.

Here is the HTML code:

        <script src="script.js"></script>


And here is the JavaScript code with all of the examples shown in the video as well as comments explaining each line of code:

// Create an array (this array has 4 elements)
var users = ["joe", "sally", "max", "alice"];

// The push method appends an element to the end of the array
// You can append multiple elements at a time
users.push("mary", "tom");

// The pop method removes the last element

// The shift method removes first element and shifts all
// other elements down one place (to a lower index)

// The unshift method adds an element to the beginning of the array
// and moves other elements forward one position

// Deletes a value from an array index but leaves
// a gap behind in the array (the element is changed to undefined)
delete users[1];

// Splice can add an element/elements to an array from a position
// First parameter: which index to start inserting elements at
// Second parameter: how many elements to remove
// Third parameter (or more): the elements to add

// Splice can also remove an element without leaving a gap or undefined element behind
// First parameter is the index where elements should be removed starting from
// Second parameter: how many elements to remove

// Creating a second array...
var users2 = ["billy", "mandy", "tim"];

// Concatenating (joining) two arrays...
var allusers = users.concat(users2);

Next lesson: Finding the length of arrays (and strings)