5

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?

3 Answers 3

7

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)

Sign up to request clarification or add additional context in comments.

2 Comments

When you say "apply some changes" as a reason for using map, would this include simple dom manipulation such as adding or removing classes? I've tried adding and removing classes using both options (forEach and map) and each works...
I think if you need just change attribute (class, id etc.) and don't need new list - better use forEach - my thoughts on this subject jsbin.com/hehame/1/edit?js. What is your opinion? maybe I'm wrong.
1

There is a subtle difference in which elements will be looped over between map and forEach. If the element in the array is undefined, it will not be invoked in map, but it will be invoked on forEach.

Obviously this distinction does not apply in the case of querySelectorAll, which will never return undefined 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:

var values = [].map.call(document.querySelectorAll('input'), function(el) {
    return el.value;
});

This will return an array containing the value of every element selected by querySelectorAll('input').

So you should use map when that's what you want; otherwise, use forEach.

NB that Array.prototype.every and Array.prototype.some also exist; there may be times when they would be more appropriate.

Comments

1

forEach - only iterates the array elements.

map - iterates the array elements and returns a new array. for example..

var temp = [].map.call(document.querySelectorAll('div'), function(e){
  return e.id;
  // do something
})

temp is new array having id of all div elements;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.