To loop over the results of querySelectorAll
in JavaScript, is one of the following more preferable than the other?
[].forEach.call(document.querySelectorAll('div'){
// do something
})
[].map.call(document.querySelectorAll('div'){
// do something
})
Essentially, I'm wondering if these each achieve the same result of providing access to each dom element returned from querySelectorAll
. If so, what are reasons one might want to use one over the other?
There is a subtle difference in which elements will be looped over between
map
andforEach
. If the element in the array isundefined
, it will not be invoked inmap
, but it will be invoked onforEach
.Obviously this distinction does not apply in the case of
querySelectorAll
, which will never returnundefined
in its results.So the only difference between them is that of what the function returns.
forEach
has no return value.map
executes a function on each member of the array and returns the results. So, for instance, you could do this:This will return an array containing the
value
of every element selected byquerySelectorAll('input')
.So you should use
map
when that's what you want; otherwise, useforEach
.NB that
Array.prototype.every
andArray.prototype.some
also exist; there may be times when they would be more appropriate.forEach - only iterates the array elements.
map - iterates the array elements and returns a new array. for example..
temp is new array having id of all div elements;
forEach operates on the original array elements. (If you want just iterate over all element you should use forEach)
map is running through your array, applying a function to each element, and emitting the result as a new array. (if you want to apply some changes to each element you should use map)