What is the difference between for...of and for...in loops?
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.
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 usingbreak
, 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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

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

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

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.

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

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.

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
