Random Weekend Javascript Musings: "for... in"

edit: Well what do you know; I was doing some light reading of Underscore.js’ documentation (yes, the things that I do in my free time…). But! I found out that Underscore.js has an Object Function to retrieve the names of it’s keys. Link.

_.keys({one: 1, two: 2, three: 3});<br></br>  
=> ["one", "two", "three"]```

 

 

We’re getting into NodeJS concepts and exercises in class, and with that, we’ve been looking at JSON as a data format. ‘For loops’ are pretty standard examples in class to loop over the values in a Javascript object, and that’s when I had the random thought: “*what if I want to get the name of the key? How do I do that?*“.

Of course, that led to some research and I came across the for…. in loop. I’m pretty sure I’d learned it before in my codecademy or pre-OCCS prep work, but since it hasn’t been used so far in class, I decided to really dig into it. I really enjoyed this read: [Exploring Javascript For-In Loops](https://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/)

Anyways, so here’s a method of getting access to the name of keys in an object:

`for (var variable in objectExpression) {statement}`

var myObj = {a: 1, b: 2, c: 3};


for (var property in myObj) {


console.log(property + ': ' + myObj[property]);


}

//console:

```

//a: 1<br></br>
//b: 2<br></br>
//c: 3```

 

Be warned. Using for… in loops can cause prototype extensions of your objects to show up. I don’t wholly understand this concept since we haven’t learned about prototypes yet, but here’s a note nevertheless. Yes, more research lined up for me this afternoon =p

var arr = ['a','b','c'], indexes = [];


Array.prototype.each = function() {/blah/};


for (var index in arr) {


indexes.push(index);


}

indexes; //["0", "1", "2", "each"] whoops!```

Read more on Exploring Javascript For-In Loops

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!