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 autoload helper files with composer?

What is YAGNI?

How to force gzip compression in Apache with .htaccess

How to get a route to directly show a view?

What are Template literals (Template strings) in JS?

How to increment a value in the database

How to hide directory listing in .htaccess?

How to get the type of a variable in JS?

How to output (echo/print) content in PHP

How to remove .php from the end of URLs with .htaccess