Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does each mean in JavaScript?

Tags:

javascript

myObj.FirstName = 'Phillip',
myObj.LastName = 'Senn';
for (var X in myObj) // FirstName LastName
for each (var X in myObj) // Phillip Senn

Q: Mentally, how do you read these two statements?

like image 568
Phillip Senn Avatar asked Apr 27 '11 02:04

Phillip Senn


People also ask

What is the meaning of each () in JavaScript?

Definition and Usage The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

What is the meaning of each in jQuery?

The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.

Can we use foreach in jQuery?

Learn how to loop through elements, arrays and objects with jQuery using the $. each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

How break out of jQuery each?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.


3 Answers

The first one (for ( in )) is reading property names from the object.

So you may read it as for each property in myObj, assign it to x.

The second one (for each ( in )) is reading values of the properties in the object.

This one may be read as for each property's value in myObj, assign it to x.

Note that for each has limited browser support.

Also note that if extra properties are appearing in for ( in ), it is because it will look up the prototype chain for extra enumerable properties (and someone may have augmented Object, for example).

You can mitigate this with...

for (var x in myObj) {
   if ( ! myObj.hasOwnProperty(x)) {
       continue;
   }
   // Now you are sure the property is of `myObj`
}

jsFiddle.

like image 68
alex Avatar answered Oct 09 '22 08:10

alex


for (var a in b) is a way for getting the indices a of the given array b. When I'm muttering to myself as I read through code, I usually say something like "for every X in myObj".

If you use the each keyword, you will retrieve the values of the object (or array) in myObj. If you omit it, myObj will contain the keys (or array indices).

like image 37
Zach Rattner Avatar answered Oct 09 '22 09:10

Zach Rattner


for(var X in myObj)

For every member (key) in myObj

for each(var X in myObj)

For each member in myObj, get its value

like image 45
Demian Brecht Avatar answered Oct 09 '22 08:10

Demian Brecht