javascript: each vs in

For vs forEach() vs for/in vs for/of in JavaScript

In this article, we will discuss the differences between for vs forEach() vs for/in vs for/of in JavaScript.

for loop

for loop is the most basic looping structure in JavaScript. It is used to iterate over an array or object.

Syntax:

for (initialization; condition; increment/decrement) { // code block to be executed }

Example:

const arr = [1, 2, 3, 4, 5]; 
for (let i = 0; i < arr.length; i++) { 
 console.log(arr[i]); 
}

Output:

1 2 3 4 5

forEach()

forEach() is an array method in JavaScript. It is used to iterate over an array.

Syntax:

array.forEach(function(currentValue, index, arr), thisValue)

Example:

const arr = [1, 2, 3, 4, 5]; 
arr.forEach(function(value, index, array) { 
 console.log(value); 
});

Output:

1 2 3 4 5

for/in

for/in is used to iterate over the properties of an object.

Syntax:

for (variable in object) { // code block to be executed }

Example:

const obj = { a: 1, b: 2, c: 3 }; 
for (let key in obj) { 
 console.log(key); 
}

Output:

a b c

for/of

for/of is used to iterate over the values of an iterable object.

Syntax:

for (variable of object) { // code block to be executed }

Example:

const arr = [1, 2, 3, 4, 5]; 
for (let value of arr) { 
 console.log(value); 
}

Output:

1 2 3 4 5

Differences between for vs forEach() vs for/in vs for/of in JavaScript

for forEach() for/in for/of for loop is used to iterate over an array or object. forEach() is used to iterate over an array. for/in is used to iterate over the properties of an object. for/of is used to iterate over the values of an iterable object. for loop is used to iterate over an array or object. forEach() is used to iterate over an array. for/in is used to iterate over the properties of an object. for/of is used to iterate over the values of an iterable object. for loop is used to iterate over an array or object. forEach() is used to iterate over an array. for/in is used to iterate over the properties of an object. for/of is used to iterate over the values of an iterable object. for loop is used to iterate over an array or object. forEach() is used to iterate over an array. for/in is used to iterate over the properties of an object. for/of is used to iterate over the values of an iterable object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: