Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (6.1k points)
I have confusion between array splice and slice in Javascript. Please tell me from the scratch about it.

1 Answer

0 votes
by (11.7k points)
edited by

Whenever we want to retrieve or remove certain elements from an array in javascript, splice and slice methods are used. 

Slice Method: This method slices(extracts) the array and returns out the new array.

Syntax: array.slice( Start  [,end] );

Start: It always starts from zero index from where slicing begins, in case of negative index, start begins from the last of the sequence.

End: It is based on zero index where slicing needs to be stopped. 

Return Value: It returns the extracted or sliced array according to the values entered by the users. 

Example: 

<html>

   <head>

      <title>JavaScript Array slice Method</title>

   </head>

   

   <body>   

      <script type = "text/javascript">

         var arr = ["Plane", "Car", "Bus", "Train", "Truck"];

         document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); 

         document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) ); 

      </script>      

   </body>

</html>

Output Snippet:

arr.slice( 1, 2) :Car

arr.slice( 1, 3) :Car, Bus

Splice Method: It is used to make changes in the original array by modifying it where it can take any number of arguments.

<script>

    var webDev = ["C", "C++", "Python", "Java"];

  

    document.write(webDev + "<br>");

  

    var removed = webDev.splice(2, 1, 'Node', 'Angular')

  

    document.write(webDev + "<br>");

    document.write(removed + "<br>");

  

    // inserting from 2nd, no removing

    //ending index

    webDev.splice(-2, 0, 'Angular')

    document.write(webDev)

</script>  

Output:

C, C++, Python, Java

C, C++, Node, Angular,Java

JS

C,C++, Node, React, Angular, Java

Want to become an expert in web technology, check out the Web Development Training offered by Intellipaat.

Related questions

0 votes
1 answer
asked Feb 7, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Feb 23, 2021 in Java by rahulnayar01123 (6.1k points)
0 votes
1 answer
asked Feb 18, 2021 in Linux by rahulnayar01123 (6.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...