Articles → JAVASCRIPT → Splice functions in JavaScript

Splice functions in JavaScript






Purpose





Syntax




Picture showing the syntax of splice function in JavaScript

Click to Enlarge

  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

Click to Enlarge


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
      </script>
   </head>
   <body>
   </body>
</html>




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

Click to Enlarge


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250