Open In App

How does Array.prototype.slice.call work in JavaScript ?

Array.prototype.slice.call()

Array.prototype.slice.call() is a method in JavaScript, It is used to convert an array-like or iterable object into a genuine array. It allows you to extract a portion of an array or an array-like object and return a new array. This technique is often used to manipulate and work with non-array objects to convert them into usable arrays.

Syntax:



Array.prototype.slice.call( arrayLikeObject, startIndex, endIndex );

Parameters: This method accepts three parameters as mentioned above and described below:

Working of Array.prototype.slice.call work in JavaScript



Example 1:




// Javascript program to illustrate
// use of Array.prototype.slice.call()
  
function func() {
  
    // Original string
    const str = "Hello,World";
      
    // Extrating 'hello' in the form array
    const result = 
        Array.prototype.slice.call(str, 0, 5);
    console.log(result);
}
func();

Output
[ 'H', 'e', 'l', 'l', 'o' ]

Explanation:

Example 2:




// Javascript program to illustrate
// use of Array.prototype.slice.call()
  
function func() {
  
    // Object with integer as key
    const arrayLike = { 
        0: 'Burger', 1: 'Pizza'
        2: 'Chawmin', 3: 'Momos', length: 4 };
          
    // Extracted array
    const extractedArray = 
        Array.prototype.slice.call(arrayLike, 1, 3);
    console.log(extractedArray);
}
func();

Output
[ 'Pizza', 'Chawmin' ]

Conclusion: In simple terms, when you have things in your code that aren’t exactly arrays but act like them (like collections of web page elements), you can use Array.prototype.slice.call() to make them work like real arrays.


Article Tags :