codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript — The difference between ForEach, and For…In

Brandon Morelli
codeburst
Published in
3 min readNov 26, 2017

The For Loop

for (i = 0; i < 10; i++) { 
// do something
}

ForEach

const arr = ['cat', 'dog', 'fish'];for (i = 0; i < arr.length; i++) { 
console.log(arr[i])
}
// cat
// dog
// fish
const arr = ['cat', 'dog', 'fish'];arr.forEach(element => {
console.log(element);
});
// cat
// dog
// fish

For…In

for (variable in object) {  
// do something
}
const obj = {  
a: 1,
b: 2,
c: 3,
d: 4
}

for (let elem in obj) {
console.log( obj[elem] )
}
// 1
// 2
// 3
// 4
for (let elem in obj) {
console.log(`${elem} = ${obj[elem]}`);
}
// a = 1
// b = 2
// c = 3
// d = 4
const arr = ['cat', 'dog', 'fish'];for (let i in arr) {  
console.log(arr[i])
}
// cat
// dog
// fish
const string = 'hello';for (let character in string) {  
console.log(string[character])
}
// h
// e
// l
// l
// o

Closing Notes:

If this post was helpful, please click the clap 👏button below a few times to show your support! ⬇⬇

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (16)

Write a response