Home >Web Front-end >JS Tutorial >What's the Difference Between JavaScript's `for...in` and `for...of` Loops?

What's the Difference Between JavaScript's `for...in` and `for...of` Loops?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 20:48:15581browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn