Splice function not behaving as expected

Hi,

I was messing around with the following bit of code:

var x = [“a”, “b”, “c”, “d”];
var y = x.splice(0, 3, “string”);
console.log(y);

With this set up I was getting [“a”, “b”, “c”] printed out.

As I understand, the first argument in the splice function is the index where the operation will begin. The second (optional) argument is for how many elements will be removed. Then the arguments which follow are the elements that are to be added.

I was messing around with the parameters and the splice function was not behaving the way I expected. It seemed to be behaving more like a slice, which is confusing.

Anyways, I hope someone can clear this up for me. I feel like I’m missing something obvious here :expressionless:

To see the results you are expecting, try console logging Var x. Var y holds the items you have removed from Var x.

‘The splice() method adds/removes items to/from an array, and returns the removed item(s).’
https://www.w3schools.com/jsref/jsref_splice.asp

1 Like

This should help you see what’s going on in the code above.

var x is just the array. var y = x.splice(0, 3, “string”); is saying start at 0 (“a”) and remove 3 (“a, b, c”) and insert “string”.