Table of contents:

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

Push

Push it a method on an array that added items to the end of the array. So in this code, we’ve created values as a three-element 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 executing value.pop we take the last element, in this case, c, off of the array, and store it in the variable last. When we log out last, we get c.

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

Shift

The shift moves the entire array. We can shift of shift() method as shifting the entire array to the left one element, and it takes the first element off the array. We calling values.shift, and we’re assigning 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 added 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 arguments. 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 a new array and that new array is stored in the variable newValue. When we log out newValue we get our slice, which is only item b. The item at index 2, the end position is not including 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

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee