Lee
Lee

Reputation: 3969

jQuery $.each vs. JavaScript .forEach

Take the following two ways of removing an array of elements from the DOM using jQuery:

var collection = [...]; //  An array of jQuery DOM objects

// Using jQuery iteration
$(collection).each(function(index, element) { element.remove(); });

// Or as pointed out by Barmar
$(collection).remove();

// Using native iteration
collection.forEach(function(element) { element.remove(); });

Is there any real difference operationally? I'd expect, unless the browser interpreter/compiler is clever enough, that there would be additional unnecessary overhead with the former method, albeit probably minor if the array is small.

Upvotes: 27

Views: 35379

Answers (4)

dpix
dpix

Reputation: 3103

Operationally is a bit vague but here is how $.each is implemented.

each implementation

[].forEach() would most likely be implemented in native code for each browser.

Without doing performance testing, they are pretty similar. Although if you can remove jQuery altogether that is at least a few kb the browser does not need to load.

Upvotes: 17

Tal
Tal

Reputation: 1231

Performance wise they both are similar Perf test

forEach is implemented native in the Browser which makes it easier to maintain for non-jquery developers while on the other hand each offers better readability.

Upvotes: 4

Eric
Eric

Reputation: 131

The comments on the original question are good for your specific scenario of wanting to remove individual items.

On a more general note, some other differences:

1) Array.forEach() obviously requires that you're iterating across an array. The jQuery approach will let you iterate across the properties of an object.

2) jQuery.each() allows short-circuiting. Check out this post that mentions use of "some()" and "every()" for doing similar things with pure js:

How to short circuit Array.forEach like calling break?

Upvotes: 6

Andy Ray
Andy Ray

Reputation: 32066

Array.forEach is a method that iterates over native Javascript arrays.

jQuery collection.each is an iteration method implemented by hand by the jQuery team. a jQuery collection is not an array.

This was also more relevant when jQuery first came out, and Array.forEach was not implemented in any browsers.

Upvotes: -2

Related Questions