Explain the differences between for (..in) and for (..of) statement in JavaScript
Last Updated :
27 Dec, 2023
Often in a JavaScript script, we iterate over some objects of a few built-in classes like Arrays, Dictionaries, Strings, Maps, etc. We iterate the objects using loops.
JavaScript supports different kinds of loops:
In this article, we will be learning about the difference between these two:
The JavaScript for (..in) statement loops through the enumerable properties of an object. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor’s prototype.
Syntax:
for (variable in object)
statement
Example: This example shows the use of a for-in loop.
Javascript
let person = {
firstName: "GeeksforGeeks" ,
lastName: "A Computer Science Portal for Geeks" ,
rank: 43
};
let userId = "" ;
let i;
for (i in person) {
userId += person[i];
console.log(userId);
}
|
Output
GeeksforGeeks
GeeksforGeeksA Computer Science Portal for Geeks
GeeksforGeeksA Computer Science Portal for Geeks43
This for (..of) statement lets you loop over the data structures that are iterable such as Arrays, Strings, Maps, Node Lists, and more. It calls a custom iteration hook with instructions to execute on the value of each property of the object.
Syntax:
for (variable of iterable) {
statement
}
Example: This example shows the use of a for-of loop.
Javascript
let text = [
"GeeksforGeeks" ,
" A Computer Science Portal for Geeks " ,
"43"
];
let userId = "" ;
let i;
for (i of text) {
userId += i;
console.log(userId);
}
|
Output
GeeksforGeeks
GeeksforGeeks A Computer Science Portal for Geeks
GeeksforGeeks A Computer Science Portal for Geeks 43
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...