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?
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
Array.splice
function by itself returns the range of elements you have starting from the first argument and ending at the second argument. Everything that comes after the second argument automatically is being added at the end of your original array, BUT it is not returned as a result of the operation.
const numbers = [1, 2, 3];
console.log(numbers.splice(0, 0, 4, 5)) // <- prints nothing because your sequence is from 0 to 0.
splice
method doesn't return the output, rather modifies the original array.