For…In loop vs For…Of loop

For…of loop is comes with the JavaScript ES6. Only new and updated modern browser is supports the For…of loop. Wherever JavaScript supports the For…in loop from long time.

For…in loop is loop on the key of the array, where as the for…of loop is loop on the value of the array.

Example:

var array = ["A", "B", "C", "D", "E"];

document.write("For In loop returns: Key <br/>");
for (var key in array) {
	document.write(key + ", ");
}

document.write("<br/>For Of loop returns: Value <br/>");
for (var value of array) {
	document.write(value + ", ");
}

//For In loop returns: Key 
//0, 1, 2, 3, 4, 
//For Of loop returns: Value 
//A, B, C, D, E,

In above example I created the array, First I loop on the array using for…in loop so every time when loop over array it point to the next index of the array and assign that index to the key variable so key variable have the one of the index of the array.

Whereas, the for…of loop also loop over the array and points to the value of the array so it assign the current value to the value variable of the loop.

For…in can loop over the object and returns the key of it, whereas the For…of loop can not loop over the object. Because the For…of loop over only the Symbol.iterator types of the object.

Array has the Symbol.iterator function inside it where as the simple object can not have the Symbol.iterator function inside it so For…of loop can not work on it.

If you used the For…of loop over the simple object than you get the error like this: object[Symbol.iterator] is not a function.

Example:

var object = { FirstName: "James", LastName: "Bond" };

document.write("For In loop returns: Key <br/>");
for (var key in object) {
	document.write(key + ", ");
}

document.write("<br/>For Of loop returns: Value <br/>");
for (var value of object) {
	document.write(value + ", ");
}

//For In loop returns: Key 
//FirstName, LastName, 
//For Of loop returns: Value

and you will also get the error like this:

Uncaught TypeError: object[Symbol.iterator] is not a function

Browser Support:

For…in loop supports from the IE6+, Google Chrome, Firefox, Edge, Opera and Safari
For…of loop supports from the latest Chrome 51, Firefox 13, Opera 25, Safari 7.1 and Edge 12 (IE not supports)

I hope you enjoyed this article, Please comment down your review about this.

Happy Coding...

🙂