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 have a whitelist of IP addresses that can access files in .htaccess

How to find the average value of items in a Laravel Collection?

How to add the default charset to UTF-8 in .htaccess

How to eager load multiple levels of relationships in Eloquent?

How to block access to certain referrers in Apache using .htaccess

How to Extract Query String (from a URL) Into an Associative Array in PHP

How to destroy or remove a cookie in PHP

What are route patterns in Laravel?

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

How to output (echo/print) content in PHP