Articles → JAVASCRIPT → Splice Functions In Javascript

Splice Functions In Javascript






Purpose





Syntax




Picture showing the syntax of splice function in JavaScript


  1. The first parameter indicates the index of the array where the item can be added or removed.
  2. The second parameter is the count of the number of elements to be deleted. If the count is zero then it means that we are adding the value in an array.
  3. The third parameter is an array of items to be inserted.

Add An Element In An Array




    <!DOCTYPE html>
    <html lang="en">
        <head>
            <script>
         const months = ['Jan', 'March', 'April', 'June'];
         
         months.splice(1, 0, 'Feb'); // => Inserts the value at index 1
         months.splice(2, 0, 'Feb'); // => Inserts the value at index 2
         months.splice(3, 0, 'Feb'); // => Inserts the value at index 3
         
         console.log(months);
      </script>
        </head>
        <body></body></html>




Picture showing the array after an element is added in an array using the Splice function



Removing Elements In An Array




        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Bootstrap Example</title>
                <script>
         const months = ['Jan', 'March', 'April', 'June'];
                  
         months.splice(3, 1, 'May'); // => Delete
         console.log(months);
      </script>
            </head>
            <body></body></html>




Picture showing the array after an element is removed in an array using the Splice function



Posted By  -  Karan Gupta
 
Posted On  -  Sunday, September 5, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250