0

I'm trying to chain methods of an Array object together but it won't let me.

var arr = [1,2,3];
arr.splice(-3, 1, 'foot').splice(arr.length,0, 'hand');
console.log(arr) // ['foot', 2, 3]

//trying to get ['foot', 2, 3, 'hand']

This doesn't work. I have to split up the second splice onto a new statement. Why doesn't this work? I've seen chaining done many times in JavaScript code.

inthenameofmusik
  • 617
  • 1
  • 4
  • 16

1 Answers1

2

Simply because Array.prototype.splice returns an array containing the deleted elements, as you can find on its documentation page.

So basically some methods allow chaining and some dont. If that is the first time you use them, you can refer to the doc.

To be more precise, most methods of an Array create a new Array (at the exception of splice), so it's not technically a chaining since you don't apply different methods on the same instance of the same array. Typical cloning-chaining methods are filter, map, find.

floribon
  • 19,175
  • 5
  • 54
  • 66
  • is there a property I can find to tell whether an array method is chainable? Or should I assume any method that returns a new array is chainable? – inthenameofmusik May 16 '16 at 12:34
  • Again, you can use array methods on any array, so if a method returns an array then you can "chain" it. However since it is a new array it won't always do what you expect, that's why it's important to read the doc (or do some tests) before. For instance you did chain two `splice` calls, but not with the result you were expecting. – floribon May 17 '16 at 09:43