Array methods in JavaScript
by danielkwood
HTML
<html>
<head>
<title>Arrays</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
JavaScript
// 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);