What is the difference between for...of and for...in statements in JavaScript?



for…in loop

The “for...in” loop is used to loop through an object's properties.

Here’s the syntax −

Syntax

for (variablename in object) {
statement or block to execute
}

You can try to run the following example to implement ‘for-in’ loop. It prints the web browser’s Navigator object

Example

Live Demo

<html>
<body>
<script>
var aProperty;
document.write("Navigator Object Properties<br /> ");

for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
</script>
</body>
</html>

for…of loop

The “for…of” loop is used to loop through iterable objects, which includes Map, Array, arguments, etc.

Syntax

Here’s the syntax −

for (variablename of iterable){
statement or block to execute
}

Example

Here’s an example showing iteration with for…of loop

Live Demo

<!DOCTYPE html>
<html>
<body>
<script>
let itObj= [20, 30, 40, 50];

for (let res of itObj) {
res += 1;
document.write("<br>"+res);
}
</script>
</body>
</html>

Output

21
31
41
51

Advertisements