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:
<html> <head> <title>Arrays</title> <script src="script.js"></script> </head> <body> </body> </html>
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 users.push("bob"); // You can append multiple elements at a time users.push("mary", "tom"); console.log(users); // The pop method removes the last element users.pop(); console.log(users); // The shift method removes first element and shifts all // other elements down one place (to a lower index) users.shift(); console.log(users); // The unshift method adds an element to the beginning of the array // and moves other elements forward one position users.unshift("jim"); console.log(users); // Deletes a value from an array index but leaves // a gap behind in the array (the element is changed to undefined) delete users[1]; console.log(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 users.splice(2,0,"sam","sarah"); console.log(users); // 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 users.splice(1,1); console.log(users); // Creating a second array... var users2 = ["billy", "mandy", "tim"]; // Concatenating (joining) two arrays... var allusers = users.concat(users2); console.log(allusers);
Next lesson: Finding the length of arrays (and strings)