Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Working with Objects and Properties > Enumerate (Loop Over) an Object’s Prop...

Enumerate (Loop Over) an Object’s Properties using the for in Loop

By using for in, we can loop over each property in an object. In the code below, we are using the for in loop to retrieve the property names from the cody object.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var cody = {
    age : 23,
    gender : 'male'
};

for (var key in cody) { // key is a variable used to represent each property name
   // avoid properties inherited from the prototype chain
    if(cody.hasOwnProperty(key)) {
        console.log(key);
    }
}

</script></body></html>

Notes

  • The for in loop has a drawback. It will not only access the properties of the specific object being looped over, but will also include in the loop any properties inherited (via the prototype chain) by the object. Thus, if this is not the desired result (and most of the time it is not), we have to use a simple if statement inside of the loop to make sure we only access the properties contained within the specific object we are looping over. This can be done by using the hasOwnProperty() method, inherited by all objects.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint