Languages

JavaScript - what's the use of Array.prototype.slice.call(array, 0)?

0 points
Asked by:
Remy-Lebe
832

Recently I was browsing JavaScript solutions and came up with the following line of code:

var array = Array.prototype.slice.call(array, 0);

What is the use of this line of code?

I checked up what the functions are, but I found that it just returns all elements of the array, it doesn't really do anything at all.

1 answer
0 points
Answered by:
Remy-Lebe
832

It is used to convert NodeList to Array type.

When you get elements from DOM using e.g querySelectorAll() method or childNodes property it usually returns a NodeList.

NodeList is almost like an array but not exactly. It has a length property like an array and a methods to access an object at the given index (also available using array notation e.g [index]). However, NodeList is automatically updated when the document changes.

Practical example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="container">Text node<span></span><div></div></div>
  <script>

    var container = document.querySelector('#container');
    var nodes = container.childNodes; // nodes variable is a NodeList

    console.log(nodes instanceof NodeList);  // true
    
    var array = Array.prototype.slice.call(nodes, 0); // converts NodeList to Array
    
    console.log(array instanceof NodeList);  // false
    console.log(array instanceof Array);     // true

  </script>
</body>
</html>

 

See also

  1. JavaScript - convert NodeList to Array

References

  1. Document.querySelectorAll() - Web APIs | MDN
  2. Node.childNodes - Web APIs | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join