Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Arrays Splice

What is the difference between use .splice and myarray[index] for replace values inside array?

I this video Jim explains that you can replace values with the splice method like this:

my_array.splice(index, 1, "my replace");

But you can also do it just with

my_array[index] = "my replace";

My question is, what is the difference? maybe does it affects the performance? is one of those faster (optimized) or they are just the same thing and does not matter what you use for replace a value in an array?

Thanks for you help Sebastian

1 Answer

In the example you gave both techniques do indeed provide the same result. I am not entirely sure, but I expect that my_array[index] = "my replace"; is the faster of the two options.

The main difference is that splice will actually return the value(s) removed from the array. Splice can also replace a larger number of values in an array with one line of code (no repeating "my_array[x] = y" for every new value)

It is also a versatile method that can be used for more than just replacing values.

Example:

var array = [1,2,3,4,5,6];

var removedValues = array.splice(2, 3, "a", "b", "c");

//array will now contains [ 1, 2, "a", "b", "c", 6 ]

//removedValues will contain [ 3, 4, 5 ]