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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-14 09:53:11865browse

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

Understanding the Distinction Between for...in and for...of Statements

In the realm of JavaScript looping, for...in and for...of statements often generate confusion. While for...in has been a cornerstone for iterating over properties, for...of emerged in ES6 to specifically target values. This article delves into the key differences between these two constructs.

for...in: Traversing Property Names

For...in loops iterate over the enumerable property names of an object. As demonstrated in the example, it successfully logs "0", "1", "2", and "foo", which represent the index keys of the array and the "foo" key of the array object.

for...of: Extracting Property Values

In contrast, for...of employs an object-specific iterator to traverse the values generated by that iterator. In the example, the array iterator yields only the values within the array, namely "3", "5", and "7". This behavior stems from the fact that iterators are designed to focus solely on values.

Non-Iteration of Non-Index Properties

Notably, for...of does not iterate over non-index properties. In the example, the "foo" property, which contains the value "hello", is not logged. This is because the array iterator only yields values associated with the array's indices.

Example: Value-Focused Iteration

To illustrate, the following loop should log the array values as well as the "foo" property value, but it logs only the array values:

for (var i of arr) {
  console.log(i); // logs "3", "5", "7"
}

This behavior reinforces the understanding that for...of is purpose-built to iterate over values, excluding non-index properties.

The above is the detailed content of What's the Key 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