Press ESC to close

JavaScript splice

0 1579

The JavaScript splice method adds and removes elements to an array starting from a specified location.

The syntax is as follows: array.splice(index, q, element1,…, elementN).

Where index represents the index from which to start and can be a negative value, which indicates that it starts from the end of the array.

The quantity q represents the quantity of items to be deleted, and if it is set to 0, or an unspecified value, no items are deleted. Otherwise, as many elements as specified are deleted.

Finally element1 … elementN are the elements to be included in the array.

The index parameter is required, while q and elements are optional parameters.

JavaScript splice – first example

Remove 3 elements from a 7-element array, starting at position 1, using the splice() method.

Let’s start with the following array of 7 numbers:



var numbers = [5,4,3,2,6,9,62];

Now to delete the elements starting from position 1, we use the splice () method and then we display the result, for convenience, in the browser console.



numbers.splice(1,3);
console.log(numbers);

So we used the splice method using the optional q parameter.

JavaScript splice – second example

Add 2 elements to an array of 7 numbers, starting from position 3 and eliminating only the third.

So, always starting from this array of numbers:



var numbers = [5,4,3,2,6,9,62];

Then, we apply the splice method to insert two values, for example 15 and 20 and delete the third, in our case the number 3.

After we always display the result in the browser console.

Here is the sample code:



numbers.splice(2,1,15,20);
console.log(numbers);

Conclusion

In this lesson we have seen how to use the splice method of JavaScript, in the next lesson we will see how to deal with other methods through numerous examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Other stories

JavaScript forEach

Next Story

JavaScript reverse

Previous Story