Home > Blockchain >  Javascript splice gives different output
Javascript splice gives different output

Time:01-15

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?

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

splice method doesn't return the output, rather modifies the original array.

CodePudding user response:

JavaScript Array splice() replace original array element

array.splice(index, how_many_element, item1, ....., itemX);
const numbers = [1, 2, 3];


console.log(numbers.splice(0, 0, 4, 5)) // <- here index = 0, how_many_element = 0, deferent = 0, that is why prints nothing because your sequence is from 0 to 0.

index : The position to add/remove items; how_many_element : Number of items to be removed.

  •  Tags:  
  • Related