Home >Web Front-end >JS Tutorial >What's the Difference Between JavaScript's `for...in` and `for...of` Loops?
Understanding the Difference between (for... in) and (for... of) Statements
Introduction
Javascript offers two loop statements, (for... in) and (for... of), which serve distinct purposes in iterating over objects and data structures.
for... of: Iterating Over Property Values
The (for... of) statement, introduced in ES6, provides a convenient way to iterate over the values of an object's properties. Unlike (for... in), which loops over property names, (for... of) focuses specifically on property values.
This distinction becomes clear in the example provided:
var arr = [3, 5, 7]; arr.foo = "hello"; for (var i in arr) { console.log(i); // logs "0", "1", "2", "foo" } for (var i of arr) { console.log(i); // logs "3", "5", "7" }
While (for... in) logs both numeric indices ("0", "1", "2") and the custom property "foo" (ES6 iterators typically exclude keys), (for... of) only logs the numeric property values ("3", "5", "7"). The reason for this is that (for... of) utilizes an object-specific iterator that focuses on property values.
In summary, (for... of) offers a concise and value-centric way to iterate over properties in an object. It skips non-index properties, such as the "foo" property in the example, and directly provides the property values as loop iterations.
The above is the detailed content of What's the Difference Between JavaScript's `for...in` and `for...of` Loops?. For more information, please follow other related articles on the PHP Chinese website!