EN
JavaScript - what's the use of Array.prototype.slice.call(array, 0)?
1
answers
0
points
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
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
References
0 comments
Add comment