JavaScript splice function

JavaScript splice function

    With JavaScript splice() function, we can change an array.  With this function, you can add or remove a value from the array given with a specific index location in the array.

    The syntax structure is 

    arr.splice(index, count, [items...]);

    1. index--> from where to start to remove or add
    2. count-->whether to add or remove
    3. items--> what to add or remove. This is optional 

    If index 2, and count 0, then nothing would be removed from the below array but will add "orange" to the array.

    <!DOCTYPE html>
    <html>
    <head>
        <title>
            JavaScript splice() Method
        </title>
    </head>
      
    <body>
      
        <script>
            let arr=["apple", "banana", "milk"];
            arr.splice(2, 0, "orange");
            console.log(arr);
        </script>
    </body>
      
    </html>

    And the output would be below

    ["apple", "banana", "orange", "milk"]

    So count = 0 means don't remove. It means add something at the third place which index is 2.

    See the below example with index 3 and count 1

    <!DOCTYPE html>
    <html>
    <head>
        <title>
            JavaScript splice() Method remove item
        </title>
    </head>
      
    <body>  
        <script>
            let arr = ["apple", "banana", "milk", "juice"];
            newArr = arr.splice(3, 1);
            console.log(arr);
        </script>
    </body>
      
    </html>

    Since index is 3 and count is 1, splice function will remove an element from the fourth position ( index is 3) of the array. and the new array would be

    ["apple", "banana", "milk"]

    So if the count parameter mentioned in splice() method is non-zero, it will remove an item or items. It's totally based number of parameters. Non-zero means remove

    See more examples

    <html>
       <head>
          <title>JavaScript splice Method Example</title>
       </head>
       
       <body>   
          <script type = "text/javascript">
             var arr = ["orange", "mango", "banana", "sugar", "tea"];         
             var removed = arr.splice(2, 0, "water");
             console.log("After adding 1: " + arr );
            console.log("<br />removed is: " + removed);
             
             removed = arr.splice(3, 1);
             console.log("<br />After adding 1: " + arr );
             console.log("<br />removed is: " + removed);
          </script>      
       </body>
    </html>