What is the difference between ( for ... in ) and ( for ... of ) in javascript?

JavaScript: What is the difference between ( for ... in ) and ( for ... of ) in javascript?

A for...in loop will loop over property names (not values) in an object. However the for ... of loop will loop over iterable objects. Read on for a description of what this means:

Here is what for ... in looks like, and what it outputs:

  1. var array = [22, 33, 44];
  2. array.foo = "hello";
  3.  
  4. for (var i in array) {
  5.    console.log(i); // logs "0", "1", "2", "foo"
  6.    // notice that it does not output 22/33/44
  7. }

Notice that it outputs the property names (i.e. 0,1,2 for the 3 initial values in the array, then 'foo' (NOT hello).

Here is how it looks for for ... in...

  1. var array = [22, 33, 44];
  2. array.foo = "hello";
  3.  
  4. for (var i of array) {
  5.    console.log(i); // logs "22", "33", "44"
  6.     //it is does not log "22", "33", "44","hello"
  7. }

It only includes the initial ones (22/33/44), not foo.

A good way to remember this:

"A mnemonic: 'o'f -> not 'o'bjects, 'i'n -> not 'i'terables" (source)

When was for in added to JS

It was standardized in ES6.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about What is the difference between ( for ... in ) and ( for ... of ) in javascript?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the JavaScript language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

What are the main error types in PHP

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

How to set custom HTTP headers in Apache (by editing .htaccess)

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to see all of the options for an artisan command?

What is the difference between reference and primitive data types types in Javascript?

How to output (echo/print) content in PHP

How to set the timezone to UTC in .htaccess

Push vs Pop vs Shift vs Unshift

How to replace whitespace with a single space