Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for .. of loop (ECMAScript 6)

So new ECMAScript 6 has introduced for .. of loop syntax.

Unfortunately, there aren't many documentations out there that explains what this really does. As in how it differs from using Array.prototype.forEach or for .. in loop.

Is it just another imperative way to perform Array.prototype.forEach?

I've already read Mozilla's doc here. But still the idea is too vague to me.

Anyone cares to explain to this halfwit?

like image 522
Daniel Shin Avatar asked Sep 14 '25 13:09

Daniel Shin


1 Answers

Quick hint

for..of takes the element.

var a = ['a','b','c'];

for (let elem of a){
    console.log(elem);
}
// output: 
// 'a'
// 'b'
// 'c'

for..in takes the index.

var a = ['a','b','c'];

for (let i in a){
    console.log(i);
}
// output:
// 0
// 1
// 2

.forEach takes element and index (optional).

var a = ['a','b','c'];

a.forEach(function(elem,i){
    console.log(i + ': ' + elem);
});
// output:
// 0: 'a'
// 1: 'b'
// 2: 'c'
like image 101
TaoPR Avatar answered Sep 17 '25 04:09

TaoPR