Search code examples
javascriptarrayssplice

Javascript splice gives different output


Here is a strange behavior I encountered while using splice.

const numbers = [1, 2, 3];
numbers.splice(0, 0, 4, 5);
console.log(numbers); // This gives output [4, 5, 1, 2, 3] 

console.log([1, 2, 3].splice(0, 0, 4, 5)) // Outputs []

Why is that?


Solution

  • This is the expected behavior. splice returns the array of deleted items, in your case, there are no elements deleted. splice actually modifies the original array. Read the docs here