Javascript .splice() Explanation

So I was watching and coding along to the first stage of Gordan Zhu’s Watch and Code Series (free version) and it’s really good. He breaks down all of the steps that is needed to make a product. I’ll write a review of the whole course later, but for now, let’s move on to .splice().
Let’s look at this array:
var todo = [‘take out the trash’, ‘learn javascript’, ‘refine mobile designs’, ‘learn nodejs, mongodb, express.js, and react.js’];
Right now, it only has four items in the list.
If you want to add something, use the .push() method. So…
todo.push(‘build the BWH web app’);console.log(todo);//you would get : ‘take out the trash’, ‘learn javascript’, ‘refine mobile designs’, ‘learn nodejs, mongodb, express.js, and react.js’, ‘build the BWH web app’
…would add the argument of .push() to the end of the todo array.
What if you want to remove one or more things from an array? Why use the .splice() method of course!
Okay, I want to get rid of the first item since it doesn’t match up with the rest of them, so I would do this:
todo.splice(0,1);//[‘take out the trash’]console.log(todo);//you would get: ‘learn javascript’, ‘refine mobile designs’, ‘learn nodejs, mongodb, express.js, and react.js’, ‘build the BWH web app’
The splice() method allows one to precisely cut information out of arrays. Otherwise you would have to use a couple of methods. This way is a lot easier.
Just remember a few things when using .splice():
- the first number is where it will start (in computer world, 0 = 1);
- the second number is how many will be cut
Hope you learned some new tricks.
Until next time.