QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads “foreach” vs “for of” vs “for in” in JavaScript

“foreach” vs “for of” vs “for in” in JavaScript

In this tutorial I will tell you the difference between foreach, for of and for in loops.

A collection is an object which contains a group of elements. For example: arrays, set, list, custom collections etc.

foreach is an method that is available only in Array objects. It allows you to iterate through elements of an array. When invoked it takes a callback function and invokes the callback once for every array element. The callback can access both index and value of the array elements. foreach is available only for looping arrays.

for in is used to loop through properties of an object. It can be any object. for in allows you to access the keys of the object but doesn’t provide reference to the values. In JavaScript object properties themselves have internal properties. One of the internal properties is [[Enumerable]]. for in will only walkthrough a property if it has [[Enumerbale]] set to true. It not used to iterate elements of an collection rather used to iterate properties of objects.

for of is a new way for iterating collections. Its introduced in ES6. Earlier you had to use for or while loop to iterate through elements of an collection. For for of to work on an collection, the collection must have an [Symbol.iterator] property.

Feb 17, 2015Narayan Prusty
WordPress Post Series PluginJavaScript "yield" Keyword and "function*()" Syntax
Comments: 3
  1. Joe
    5 years ago

    Very concise and to the point. Thank you!

    ReplyCancel
  2. Kostya
    5 years ago

    Thanks for your article. Short and pretty!

    ReplyCancel
  3. John
    5 years ago

    greate article. i am wonder about this, thanks your post

    ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

7 years ago 4 Comments Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
Related Articles
  • JavaScript “for of” Loop Tutorial
  • wp_load_alloptions() Function
  • JavaScript Function Return Multiple Values
  • Horizontal and vertical Centering Using CSS
  • JavaScript “yield” Keyword and “function*()” Syntax
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license