Member-only story

The difference between .splice() and .slice

Jay Wen
2 min readJun 24, 2020

--

I can’t tell you how many times I forget the difference between “.splice” and “.slice” when I’m doing an algorithm and trying to decide which one to use. So here are some examples to help me and anybody else who struggles with remembering to understand the differences.

.slice()

  • extracts a part of the array and returns the selected elements in a new array.
  • takes in two arguments. First argument is the start and second argument is the end but does not include the given end argument.
let flowers = ['forget me nots', 'dahlias', 'roses', 'daisies', 'tulips']
flowers.slice(0, 2)
returns ['forget me nots', 'dahlias']
// this returned new array does NOT include the item on index 2 of 'roses'.
//the flower array is now changed to
['roses', 'daisies', 'tulips']
//To get the elements from the end of the array you can do this:let flowers = ['forget me nots', 'dahlias', 'roses', 'daisies', 'tulips']
flowers.slice(-3, -1)
returns ['roses', 'daisies']
//the flower array is now changed to['forget me nots', 'dahlias', 'tulips']

.splice()

  • adds or removes items into the array and returns the added or removed items
  • can take up to three arguments. First argument takes the index, the second argument takes in the amount you want to remove…

--

--

Jay Wen
Jay Wen

Written by Jay Wen

Hey! I’m a full stack software engineer. Here’s where I document my technical learning and any tips/skills I can share as I continue to learn. :)

No responses yet