Open In App

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

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • arrayLikeObject: The object that you want to convert into an array.
  • startIndex (optional): This parameter defines the starting index from where the portion is to be extracted.
  • endIndex (optional): This parameter is the index up to which the portion is to be extracted (excluding the end index).

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

  • In this example, we are creating a function named ‘func’ where we are storing our string in ‘str’ variable.
  • We are using ‘Array.prototype.slice.call’ function and passing arguments to it as our original string initial index and final index and storing the result into the ‘result’ variable.
  • At last printing results in the console.

Example 1:

Javascript




// 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:

  • In this example we are having a object type array which we need to process.
  • We are using Array.prototype.slice.call function and passing arguments as that array and initial and final index. and storing the result into the ‘result’ variable.
  • At the end we are printing the result in the console.

Example 2:

Javascript




// 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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads