Table of contents:

  1. Push
  2. Pop
  3. Shift
  4. Unshift
  5. Slice
  6. Splice

Push

Push it a method on an array that addes items to the end of the array. So in this code, we’re created values as a three-elements array, and then we’re executing value.push, and we’re passing it the element that we want to add to the end of the array, the letter d.

const values = ['a', 'b', 'c']
values.push('d')
console.log(values) // a b c d 

When we log out values, we get a, b, c, c and d.

Pop

Method pop takes the last element off an array. When execute value.pop we take last element, in this case c, off of the array, and store in the variable last. When we logout last, we get c.

const values = ['a', 'b', 'c']
const last =  values.pop()
console.log(last) // c

Shift

Shift moves entire array. We can shift of shift() method as shifting entire array to the left one element, and it takes the fisrt element off the array. We calling values.shift, and we’re assinging the result of that to first. The result will be the first element of the array, the letter a.

const values = ['a', 'b', 'c']
const first =  values.shift()
console.log(first) // a

Unshift

Starting with an array with values b and c and we call values.unshift, passing it a. So this addes the letter a to the beginning of the array. When we log out values, we get a, b, c and c.

const values = ['a', 'c']
values.unshift('a')
console.log(values) // a b c 

Slice

When we execute the value.slice and we have two argiments. The first argument is where we want to start to take our slice, which is element 1 - (element 1 is b) it’s not a, a is element 0. Ant to give us the ending element that we want to look at, which is 2, in which case that would be c.

const value = ['a', 'b', 'c']
const newValue = value.slice(1, 2)
console.log(newValue) // b

Line const newValue = value.slice(1, 2) creates new array and that new array is stored in the variable newValue. When we logout newValue we get our slice, which is only item b. The item at index 2, the end position is not include in the results. It essentially made a copy of the slice of the array without altering the original.

Splice

When we execute value.splice with two arguments. The first argument is the index of the element we want to delete, and the second argument is the number of items we want to delete.

const value = ['a', 'b', 'c']
value.splice(1, 1)
console.log(value) // a c

So index 1 is the b and let’s just delete that b by specifying one item. When we log out values, we got a and c. The b is gone. Splice can be used for inserting. For example:

const value = ['a', 'b', 'c']
value.splice(1, 0, 'foo')
console.log(value) // a foo b c

Reference:

  1. Array.prototype.slice()
  2. MDN Web Docs