Skip to content
Related Articles

Related Articles

JavaScript Array splice() Method

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 01 Dec, 2022
Improve Article
Save Article

The JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

Syntax:

Array.splice( index, remove_count, item_list )

Parameter: This method accepts many parameters some of which are described below: 

  • index: It is a required parameter. This parameter is the index from which the modification of the array starts (with the origin at 0). This can be negative also, which begins after many elements counting from the end.
  • remove_count: The number of elements to be removed from the starting index.
  • items_list: The list of new items separated by a comma operator that is to be inserted from the starting index.

Return Value: While it mutates the original array in place, still it returns the list of removed items. In case there is no removed array it returns an empty array.

Below are examples of Array splice() method. 

Example 1: 

Javascript




<script>
    var webDvlop = ["HTML", "CSS", "JS", "Bootstrap"];
      
    console.log(webDvlop);
      
    // Add 'React_Native' and 'Php' after removing 'JS'.
    var removed = webDvlop.splice(2, 1, 'PHP', 'React_Native')
      
    console.log(webDvlop);
    console.log(removed);
      
    // No Removing only Insertion from 2nd 
    // index from the ending
    webDvlop.splice(-2, 0, 'React')
    console.log(webDvlop)
</script>

Output: 

HTML,CSS,JS,Bootstrap
HTML,CSS,PHP,React_Native,Bootstrap
JS
HTML,CSS,PHP,React,React_Native,Bootstrap

Example 2:  

Javascript




<script>
    var languages = ['C++', 'Java', 'Html', 'Python', 'C'];
      
    console.log(languages);
      
    // Add 'Julia' and 'Php' after removing 'Html'.
    var removed = languages.splice(2, 1, 'Julia', 'Php')
      
    console.log(languages);
    console.log(removed);
      
    // No Removing only Insertion from 2nd index from the ending
    languages.splice(-2, 0, 'Pascal')
    console.log(languages)
</script>

Output: 

C++,Java,Html,Python,C
C++,Java,Julia,Php,Python,C
Html
C++,Java,Julia,Php,Pascal,Python,C 

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
 Supported Browsers:

  • Google Chrome 1 and above
  • Internet Explorer 5.5 and above
  • Firefox 1 and above
  • Opera 4 and above
  • Safari 1 and above

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!