User Tools

Site Tools


java-script:for-in-vs-for-of

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
java-script:for-in-vs-for-of [2023/08/10 02:52] – created odeftajava-script:for-in-vs-for-of [2023/08/11 12:22] (current) odefta
Line 18: Line 18:
 </code> </code>
  
-==== Example with an array ====+==== Example with an Array ====
 <code javascript> <code javascript>
 const arr = [10, 20, 30]; const arr = [10, 20, 30];
Line 51: Line 51:
 </note> </note>
  
 +===== For Of =====
 +
 +The **for...of** loop ;;;iterates over the values;;; of an iterable object (such as an **array, set, or map**).
 +It gives you the values of the iterable directly. \\ 
 +<note warning>
 +It can't be used directly on plain objects without using methods like Object.keys, Object.values, or Object.entries.
 +</note>
 +
 +==== Example with an Array ====
 +
 +<code javascript>
 +const arr = [10, 20, 30];
 +
 +for (const value of arr) {
 +  console.log(value); // Logs '10', '20', '30'
 +}
 +</code>
 +
 +==== Example with an Object ====
 +
 +The **for...of** loop is designed to work with iterable objects, such as arrays, strings, maps, sets, etc. Ordinary objects are not iterable by default, so **attempting to use for...of with an object will lead to an error.**
 +
 +However, you can convert an object's keys, values, or key-value pairs into an array and then iterate over that array with a for...of loop. \\ 
 +Example:
 +<code javascript>
 +const person = {
 +  name: 'Alice',
 +  age: 30,
 +  profession: 'Engineer',
 +};
 +
 +// Iterate over keys
 +for (const key of Object.keys(person)) {
 +  console.log(`Key: ${key}`);
 +}
 +
 +// Iterate over values
 +for (const value of Object.values(person)) {
 +  console.log(`Value: ${value}`);
 +}
 +
 +// Iterate over key-value pairs
 +for (const [key, value] of Object.entries(person)) {
 +  console.log(`Key: ${key}, Value: ${value}`);
 +}
 +
 +// Output:
 +// Key: name
 +// Key: age
 +// Key: profession
 +// Value: Alice
 +// Value: 30
 +// Value: Engineer
 +// Key: name, Value: Alice
 +// Key: age, Value: 30
 +// Key: profession, Value: Engineer
 +</code>
 +
 +In this example, **Object.keys(person)**, **Object.values(person**), and **Object.entries(person)** return arrays of the object's keys, values, and key-value pairs, respectively, allowing you to iterate over them with a **for...of** loop.
 +
 +===== Conclusion =====
 +
 +  * Use **for...in** to iterate over the **keys** of an **object** (including non-array objects).
 +  * Use **for...of** to iterate over the **values** of iterables like **arrays, sets, and maps**.
 +  * Be cautious using **for...in with arrays**, especially if you have added custom properties, as it can lead to unexpected results.
  
  
  
java-script/for-in-vs-for-of.1691625125.txt.gz · Last modified: 2023/08/10 02:52 by odefta