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

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

301 Redirect a single URL in .htaccess to a new location

How to show (or log) all SQL queries executed by Laravel

How to split a string into an array, in JS

What are the predefined variables in PHP?

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

What is YAGNI?

When is __destruct called in PHP?

How to set the timezone to UTC in .htaccess

How to force SSL in Apache's .htaccess?