亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
for...of loops over iterable values
Key Differences Summary
When to Use Which?
One Common Pitfall
Home Web Front-end JS Tutorial What is the difference between for...of and for...in in JavaScript?

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

Aug 01, 2025 am 05:44 AM
cycle

for...in is used to traverse an enumerable attribute, returning the attribute name (key), suitable for objects and arrays, but the array may contain non-numeric indexes and custom attributes, and is not recommended for array value traversal; 2. for...of is used to traverse iterable objects (such as arrays, strings, Map, Set, etc.), and returns the actual value through Symbol.iterator, and is not suitable for ordinary objects; 3. The difference is that for...in is for object attribute keys, for...of is for iterable values, and should be selected according to the data type and requirements. for...in is suitable for processing object keys, and for...of is suitable for obtaining values of arrays or strings, etc.

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

The difference between for...of and for...in in JavaScript comes down to what they iterate over — they may look similar, but they serve different purposes.

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

for...in loops over object properties

for...in is designed to loop through the enumerable properties of an object, including inherited ones (from the prototype chain, unless they're non-enumerable). It works best with plain objects.

 const person = {
  name: 'Alice',
  age: 30,
  city: 'New York'
};

for (let key in person) {
  console.log(key, person[key]);
}
// Output:
// name Alice
// age 30
// city New York

? Key point: for...in gives you the keys (property names) , not the values directly.

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

It can also be used on arrays, but it returns index strings , not values:

 const arr = ['a', 'b', 'c'];
for (let index in arr) {
  console.log(index); // "0", "1", "2"
}

?? But this is generally not recommended for arrays because:

What is the difference between for...of and for...in in JavaScript?
  • It may include unexpected properties if someone added them to the array object.
  • It iterates over all enumerable properties , not just numeric indices.

for...of loops over iterable values

for...of works with iterable objects like arrays, strings, maps, sets, NodeLists, etc. It gives you the actual values , not the keys.

 const arr = ['a', 'b', 'c'];
for (let value of arr) {
  console.log(value);
}
// Output:
// a
// b
// c

It works on strings too:

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

? Use for...of when you want the values from an iterable (especially arrays).

Under the hood, for...of uses the object's Symbol.iterator method to get the sequence of values.


Key Differences Summary

Feature for...in for...of
Purpose Iterate over object properties Iterate over iterable values
Returns Keys (property names) Values
Works with objects ? Yes ? No (objects aren't iterable by default)
Works with arrays ? But returns indices (as strings) ? Yes (returns actual values)
Works with strings ? Yes (returns indices) ? Yes (returns characters)
Uses Symbol.iterator ? No ? Yes

When to Use Which?

  • Use for...in when:

    • You're looping over an object's own enumerable properties.
    • You need the keys (eg, to check or manipulate property names).
     for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        // safely process own properties
      }
    }
  • Use for...of when:

    • You're working with arrays, strings, maps, sets, etc.
    • You want clean access to the values without dealing with indices or keys.
     for (let value of myArray) {
      console.log(value); // clean and clear
    }

One Common Pitfall

 const arr = ['a', 'b', 'c'];
arr.customProp = 'extra';

for (let key in arr) {
  console.log(key); // "0", "1", "2", "customProp" ← unexpected!
}

for (let value of arr) {
  console.log(value); // "a", "b", "c" ← ignores non-iterable props
}

So for...of is safe for arrays.


Bottom line:

  • for...inobjects , get keys
  • for...ofiterables , get values

Choose based on your data type and what you need.

The above is the detailed content of What is the difference between for...of and for...in in JavaScript?. 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)

A comparative study of loops and recursion in Go language A comparative study of loops and recursion in Go language Jun 01, 2023 am 09:23 AM

Note: This article compares loops and recursion from the perspective of Go language. When writing programs, you often encounter situations where a series of data or operations need to be processed repeatedly. To achieve this we need to use loops or recursion. Loops and recursions are both commonly used processing methods, but in practical applications, they each have advantages and disadvantages, so the actual situation needs to be considered when choosing which method to use. This article will conduct a comparative study of loops and recursion in the Go language. 1. Loops A loop is a mechanism that repeatedly executes a certain piece of code. There are three main types of Go language

Lambda expression breaks out of loop Lambda expression breaks out of loop Feb 20, 2024 am 08:47 AM

Lambda expression breaks out of the loop, specific code examples are needed. In programming, the loop structure is an important syntax that is often used. However, in certain circumstances, we may want to break out of the entire loop when a certain condition is met within the loop body, rather than just terminating the current loop iteration. At this time, the characteristics of lambda expressions can help us achieve the goal of jumping out of the loop. Lambda expression is a way to declare an anonymous function, which can define simple function logic internally. It is different from an ordinary function declaration,

Java Iterator vs. Iterable: A step into writing elegant code Java Iterator vs. Iterable: A step into writing elegant code Feb 19, 2024 pm 02:54 PM

Iterator interface The Iterator interface is an interface used to traverse collections. It provides several methods, including hasNext(), next() and remove(). The hasNext() method returns a Boolean value indicating whether there is a next element in the collection. The next() method returns the next element in the collection and removes it from the collection. The remove() method removes the current element from the collection. The following code example demonstrates how to use the Iterator interface to iterate over a collection: Listnames=Arrays.asList("John","Mary","Bob");Iterator

PHP returns all the values ??in the array to form an array PHP returns all the values ??in the array to form an array Mar 21, 2024 am 09:06 AM

This article will explain in detail how PHP returns all the values ??of an array to form an array. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Using the array_values() function The array_values() function returns an array of all the values ??in an array. It does not preserve the keys of the original array. $array=["foo"=>"bar","baz"=>"qux"];$values=array_values($array);//$values ??will be ["bar","qux"]Using a loop can Use a loop to manually get all the values ??of the array and add them to a new

What is the difference between foreach and for loop What is the difference between foreach and for loop Jan 05, 2023 pm 04:26 PM

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

Using vectorization to replace loops in python Using vectorization to replace loops in python Apr 14, 2023 pm 07:07 PM

All programming languages ??are inseparable from loops. So, by default, we start executing a loop whenever there is a repeating operation. But when we are dealing with large number of iterations (millions/billions of rows), using loops is a crime. You might be stuck for a few hours, only to realize later that it doesn't work. This is where implementing vectorization in python becomes very critical. What is vectorization? Vectorization is a technique for implementing (NumPy) array operations on data sets. Behind the scenes, it applies the operation to all elements of the array or series at once (unlike a "for" loop that operates one row at a time). Next we use some use cases to demonstrate what vectorization is. Find the sum of numbers##Use the loop importtimestart

What are the alternatives to recursive calls in Java functions? What are the alternatives to recursive calls in Java functions? May 05, 2024 am 10:42 AM

Replacement of recursive calls in Java functions with iteration In Java, recursion is a powerful tool used to solve various problems. However, in some cases, using iteration may be a better option because it is more efficient and less prone to stack overflows. Here are the advantages of iteration: More efficient since it does not require the creation of a new stack frame for each recursive call. Stack overflows are less likely to occur because stack space usage is limited. Iterative methods as an alternative to recursive calls: There are several methods in Java to convert recursive functions into iterative functions. 1. Use the stack Using the stack is the easiest way to convert a recursive function into an iterative function. The stack is a last-in-first-out (LIFO) data structure, similar to a function call stack. publicintfa

How to handle PHP loop nesting errors and generate corresponding error messages How to handle PHP loop nesting errors and generate corresponding error messages Aug 07, 2023 pm 01:33 PM

How to handle PHP loop nesting errors and generate corresponding error messages. During development, we often use loop statements to handle repeated tasks, such as traversing arrays and processing database query results. However, when using loop nesting, you sometimes encounter errors, such as infinite loops or too many nesting levels. This problem can cause server performance to degrade or even crash. In order to better handle such errors and generate corresponding error messages, this article will introduce some common processing methods and give corresponding code examples. 1. Use counters to

See all articles