Search code examples
javascriptfunctionmethodssplice

Why .splice() method deletes elements of different indexes?


This is my first question on stackoverflow, I am new :) learning JS. I have a question. I wrote this function:

function inverseSlice(items, a, b) {
  return items.splice(a, b);
}
inverseSlice([1, 2, 3, 4, 5, 6], 2, 4)
(4) [3, 4, 5, 6]

Why this function returns last 4 digits, when according to docs on MDN (which I read 10 times already :P) splice() method should remove here only 2 middle ones (3, 4)? It should return [1, 2, 5, 6]. Am I right? Thank You for all Your help :)


Solution

  • It's doing exactly what it advertises, it "returns an array containing the deleted elements."

    function inverseSlice(items, a, b) {
      return items.splice(a, b);
    }
    
    let array = [1, 2, 3, 4, 5, 6, 7, 8];
    
    // Deletes 4 entries starting at index 2,
    // or in other words [3,4,5,6] are snipped
    inverseSlice(array, 2, 4);
    
    console.log(array);

    Unless you keep a reference to the array you're passing in you'll never observe anything about how it ends up, you'll only get the deleted elements.