Table of Contents
for...in Loops: Iterate Over Object Keys
for...of Loops: Iterate Over Values ​​Directly
When to Use Which?
Home Web Front-end JS Tutorial What is the difference between for...of and for...in loops?

What is the difference between for...of and for...in loops?

Jun 27, 2025 am 01:16 AM

for...in loop is used to traverse the keys of an object, while for...of is used to traverse the values ​​of an iterable object. 1. for...in is suitable for ordinary objects, traversing all their enumerable attribute key names, including array indexes (returned as strings); 2. for...of is suitable for iterable objects such as arrays, strings, Map, Set, etc., and directly access element values; 3. Selection basis: If you need to process key names or check the object structure, use for...in. If you pay attention to the value itself and want the code to be concise, use for...of.

What is the difference between for...of and for...in loops?

The main difference between for...of and for...in loops lies in what they iterate over. for...in loops are used to iterate over enumerable properties of an object, such as the keys (property names) in an object or array. On the other hand, for...of loops are used to iterate over iterable objects , like arrays, strings, maps, sets, and more — essentially anything that implements the iterable protocol.


for...in Loops: Iterate Over Object Keys

When you use a for...in loop, it goes through all the enumerable string-keyed properties of an object. This makes it useful for inspecting the structure of an object — not necessarily its values.

 const obj = { a: 1, b: 2, c: 3 };

for (let key in obj) {
  console.log(key); // Outputs: a, b, c
}
  • It works on any object, including arrays.
  • The iteration order is not guaranteed to be numeric, especially with non-array objects.
  • Be cautious when using it with arrays — it iterates over the index positions as strings , not the actual values.

Common mistake:

 const arr = [10, 20, 30];
for (let i in arr) {
  console.log(i); // Outputs "0", "1", "2" — not numbers, but strings!
}

Use this loop when you need to access property names or keys, especially in plain objects.


for...of Loops: Iterate Over Values ​​Directly

This loop is designed specifically for iterable objects — things like arrays, strings, maps, sets, NodeLists, etc.

 const arr = [10, 20, 30];

for (let value of arr) {
  console.log(value); // Outputs: 10, 20, 30
}
  • It gives you direct access to the elements, not their indexes or keys.
  • Works great with data structures that implement the iterable protocol.
  • Doesn't work directly on regular objects unless you wrap them or define your own iterator.

Example with a string:

 for (let char of "hello") {
  console.log(char); // h, e, l, l, o
}

Use this loop when you just want to process each item in a collection without worrying about keys or indexes.


When to Use Which?

Here's a quick guide to help you decide which loop to use based on your needs:

  • ✅ Use for...in when:

    • You're working with a plain object and need to access keys or property names.
    • You need to inspect an object's structure (like debugging or dynamic property access).
  • ✅ Use for...of when:

    • You're dealing with an iterable like arrays, strings, maps, or sets.
    • You care about the values ​​themselves, not their keys or indexes.
    • You want clean, readable code that focuses on the data, not the mechanics.

Also note:

  • for...in can include inherited enumerable properties if the object has a prototype chain.
  • for...of can be broken out of using break , just like a normal loop.

Basically, choose based on what you're looping through and what you need from it. One isn't better than the other — they're just mean for different purposes.

The above is the detailed content of What is the difference between for...of and for...in loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1598
276
Advanced Conditional Types in TypeScript Advanced Conditional Types in TypeScript Aug 04, 2025 am 06:32 AM

TypeScript's advanced condition types implement logical judgment between types through TextendsU?X:Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[]|number[]. 2. Use distribution to build filtering and extraction tools: Exclude excludes types through TextendsU?never:T, Extract extracts commonalities through TextendsU?T:Never, and NonNullable filters null/undefined. 3

Micro Frontends Architecture: A Practical Implementation Guide Micro Frontends Architecture: A Practical Implementation Guide Aug 02, 2025 am 08:01 AM

Microfrontendssolvescalingchallengesinlargeteamsbyenablingindependentdevelopmentanddeployment.1)Chooseanintegrationstrategy:useModuleFederationinWebpack5forruntimeloadingandtrueindependence,build-timeintegrationforsimplesetups,oriframes/webcomponents

What are the differences between var, let, and const in JavaScript? What are the differences between var, let, and const in JavaScript? Aug 02, 2025 pm 01:30 PM

varisfunction-scoped,canbereassigned,hoistedwithundefined,andattachedtotheglobalwindowobject;2.letandconstareblock-scoped,withletallowingreassignmentandconstnotallowingit,thoughconstobjectscanhavemutableproperties;3.letandconstarehoistedbutnotinitial

What is optional chaining (?.) in JS? What is optional chaining (?.) in JS? Aug 01, 2025 am 06:18 AM

Optionalchaining(?.)inJavaScriptsafelyaccessesnestedpropertiesbyreturningundefinedifanypartofthechainisnullorundefined,preventingruntimeerrors.1.Itallowssafeaccesstodeeplynestedobjectproperties,suchasuser.profile?.settings?.theme.2.Itenablescallingme

Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Aug 05, 2025 am 08:30 AM

This article explores in-depth how to automatically generate solveable puzzles for the Double-Choco puzzle game. We will introduce an efficient data structure - a cell object based on a 2D grid that contains boundary information, color, and state. On this basis, we will elaborate on a recursive block recognition algorithm (similar to depth-first search) and how to integrate it into the iterative puzzle generation process to ensure that the generated puzzles meet the rules of the game and are solveable. The article will provide sample code and discuss key considerations and optimization strategies in the generation process.

How can you remove a CSS class from a DOM element using JavaScript? How can you remove a CSS class from a DOM element using JavaScript? Aug 05, 2025 pm 12:51 PM

The most common and recommended method for removing CSS classes from DOM elements using JavaScript is through the remove() method of the classList property. 1. Use element.classList.remove('className') to safely delete a single or multiple classes, and no error will be reported even if the class does not exist; 2. The alternative method is to directly operate the className property and remove the class by string replacement, but it is easy to cause problems due to inaccurate regular matching or improper space processing, so it is not recommended; 3. You can first judge whether the class exists and then delete it through element.classList.contains(), but it is usually not necessary; 4.classList

What is the class syntax in JavaScript and how does it relate to prototypes? What is the class syntax in JavaScript and how does it relate to prototypes? Aug 03, 2025 pm 04:11 PM

JavaScript's class syntax is syntactic sugar inherited by prototypes. 1. The class defined by class is essentially a function and methods are added to the prototype; 2. The instances look up methods through the prototype chain; 3. The static method belongs to the class itself; 4. Extends inherits through the prototype chain, and the underlying layer still uses the prototype mechanism. Class has not changed the essence of JavaScript prototype inheritance.

Building a Design System with Storybook and React Building a Design System with Storybook and React Jul 30, 2025 am 05:05 AM

First, use npxstorybookinit to install and configure Storybook in the React project, run npmrunstorybook to start the local development server; 2. Organize component file structure according to functions or types, and create corresponding .stories.js files to define different states in each component directory; 3. Use Storybook's Args and Controls systems to achieve dynamic attribute adjustments to facilitate testing of various interactive states; 4. Use MDX files to write rich text documents containing design specifications, accessibility instructions, etc., and support MDX loading through configuration; 5. Define the design token through theme.js and use preview.js

See all articles