Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is for each...in a statement in JavaScript?
The for each...in loop was a non-standard JavaScript feature that iterated over the values of object properties. However, it has been deprecated and removed from modern JavaScript engines.
Important: The for each...in statement is deprecated and no longer supported. Use modern alternatives like for...of, Object.values(), or forEach() instead.
Syntax (Deprecated)
The original syntax was:
for each (variablename in object) {
statement or block to execute
}
Why It Was Deprecated
The for each...in statement was:
- Non-standard and only supported in Firefox
- Confusing because it mixed concepts from
for...inand array iteration - Replaced by better, standardized alternatives
Modern Alternatives
Using Object.values() with forEach()
var myObj = {myProp1: 30, myProp2: 40};
var sum = 0;
Object.values(myObj).forEach(function(value) {
sum += value;
});
console.log(sum);
70
Using for...of with Object.values()
var myObj = {myProp1: 30, myProp2: 40};
var sum = 0;
for (var value of Object.values(myObj)) {
sum += value;
}
console.log(sum);
70
Using for...in (for keys)
var myObj = {myProp1: 30, myProp2: 40};
var sum = 0;
for (var key in myObj) {
sum += myObj[key];
}
console.log(sum);
70
Comparison of Modern Approaches
| Method | Iterates Over | Browser Support |
|---|---|---|
Object.values() |
Values | ES2017+ |
for...of |
Iterable values | ES2015+ |
for...in |
Property names | All browsers |
Conclusion
The for each...in statement is obsolete and should not be used. Modern JavaScript provides better alternatives like Object.values() with forEach() or for...of loops for iterating over object values.
Advertisements
