Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no forEach method on Object in ECMAScript 5?

ECMAScript 5's array.forEach(callback[, thisArg]) is very convenient to iterate on an array and has many advantage over the syntax with a for:

  • It's more concise.
  • It doesn't create variables that we need only for the purpose of iterating.
  • It's creates a visibility scope for the local variables of the loop.
  • It boosts the performance.

Is there a reason why there is no object.forEach to replace for(var key in object) ?

Of course, we could use a JavaScript implementation, like _.each or $.each but those are performance killers.

like image 932
Samuel Rossille Avatar asked Feb 18 '13 05:02

Samuel Rossille


People also ask

Is forEach supported in ES5?

You have five options (two supported basically forever, another added by ECMAScript 5 ["ES5"], and two more added in ECMAScript 2015 ("ES2015", aka "ES6"): Use for-of (use an iterator implicitly) (ES2015+) Use forEach and related (ES5+)

Can you use forEach on an object?

JavaScript's Array#forEach() function lets you iterate over an array, but not over an object. But you can iterate over a JavaScript object using forEach() if you transform the object into an array first, using Object. keys() , Object. values() , or Object.

Is forEach part of ES6?

ES6 introduced the Array. forEach() method for looping through arrays. You call this method on your array, and pass in a callback function to run on each iteration of the loop.


1 Answers

Well, it's pretty easy to rig up yourself. Why further pollute the prototypes?

Object.keys(obj).forEach(function(key) {   var value = obj[key]; }); 

I think a big reason is that the powers that be want to avoid adding built in properties to Object. Objects are the building blocks of everything in Javascript, but are also the generic key/value store in the language. Adding new properties to Object would conflict with property names that your Javascript program might want to use. So adding built in names to Object is done with extreme caution.

Array is indexed by integers, so it doesn't have this issue.

This is also why we have Object.keys(obj) instead of simply obj.keys. Pollute the Object constructor as that it typically not a big deal, but leave instances alone.

like image 114
Alex Wayne Avatar answered Oct 01 '22 03:10

Alex Wayne