Array.prototype.slice.call() code example

Example 1: javascript copy array

var oldColors=["red","green","blue"];
var newColors = oldColors.slice(); //make a clone/copy of oldColors

Example 2: array.slice

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

Example 3: [].slice.call(

[]    // Array object
.slice // Accessing the function 'slice' present in the prototype of Array
.call // Accessing the function 'call' present in the prototype of function object(slice)
(document.querySelectorAll('a'),0) 
    // 'call' can have arguments like, (thisArg, arg1,arg2...n). 
   // So here we are passing the 'thisArg' as an array like object,
  // that is a 'nodeList'. It will be served as 'this' object inside of slice function.
 // And finally setting 'start' argument of slice as '0' and leaving the 'end' 
// argument as 'undefined'

Example 4: slice() javascript

let ourString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
ourString.slice(0, 11);
console.log(ourString.slice(0, 11));
//Lorem ipsum

string.slice(start, end);
//Start is required. The position where to begin the extraction. 
//First character is at position 0

//End is optional. 
//The position (up to, but not including) where to end the extraction.