For of loof
in Programming on Javascript
Javascript ES6,ES7,ES8
For of loof
1.for
const friends = ["Euido", "Josh", "Jack", "Anna"];
for(let i = 0; i < friends.length(); i++){
console.log(friends[i]);
}
2.forEach
const friends = ["Euido", "Josh", "Jack", "Anna"];
friends.forEach(friend, i){
console.log(friend + i);
}
// i is index
or
const friends = ["Euido", "Josh", "Jack", "Anna"];
friends.forEach(friend => console.log(friend));
3.for of
const friends = ["Euido", "Josh", "Jack", "Anna"];
for(const friend of friends){
console.log(friend);
}
Why we use “for of”?
we can use “for of” not only array but also all of things which is iterable.
also can stop the loop using “if” as below
const friends = ["Euido", "Josh", "Jack", "Anna"];
for(const friend of friends){
if(friend === "Jack"){
break;
} else {
console.log(friend);
}
}