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 check if an object or variable is an array, in JS?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to have a whitelist of IP addresses that can access files in .htaccess

What is the max size, by default, of GET variables?

How to return JSON data to the user in Laravel?

When is __destruct called in PHP?

How to add and remove items to an array in JS?

Set PHP config Variables (like ini_set) with .htaccess

How to check if a object has a static variable defined?

How do you launch the PHP interactive shell?