{"id":24490,"date":"2024-01-08T20:24:08","date_gmt":"2024-01-08T19:24:08","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/dominando-el-bucle-for-of-en-javascript\/"},"modified":"2024-06-03T18:44:27","modified_gmt":"2024-06-03T17:44:27","slug":"dominando-el-bucle-for-of-en-javascript","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/","title":{"rendered":"Mastering the for\u2026of Loop in JavaScript"},"content":{"rendered":"<p>The JavaScript programming language is an essential part of modern web development. Its control flow structures are essential tools for any developer. Among them, the loop <code>for...of<\/code> It stands out for being an efficient and modern way to iterate over iterable elements. This article is an in-depth guide on loop usage and features <code>for...of<\/code> in JavaScript, also considering the concept of iterators in the language.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Introduccion_al_Bucle_for%E2%80%A6of\" >Introduction to the for\u2026of Loop<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#%C2%BFQue_hace_especial_al_for%E2%80%A6of\" >What makes for\u2026of special?<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Sintaxis_Basica_del_Bucle_for%E2%80%A6of\" >Basic Syntax of the for\u2026of Loop<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Ejemplo_Basico\" >Basic Example:<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Trabajando_con_Colecciones_Iterables\" >Working with Iterable Collections<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Arrays_y_NodeList\" >Arrays and NodeList<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Ejemplo_con_Arrays\" >Example with Arrays:<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Ejemplo_con_NodeList\" >Example with NodeList:<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Strings\" >Strings<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Objetos_y_la_Interfaz_Iterable\" >Objects and the Iterable Interface<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Ejemplo_con_Map\" >Example with Map:<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Control_de_Flujo_y_Desestructuracion\" >Flow Control and Destructuring<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Uso_de_break_y_continue\" >Using break and continue<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Desestructuracion_en_for%E2%80%A6of\" >Destructuring in for\u2026of<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Ejemplo_con_Objetos\" >Example with Objects:<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Iteradores_y_el_protocolo_Iterable\" >Iterators and the Iterable protocol<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Creando_objetos_iterables_personalizados\" >Creating custom iterable objects<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Mejores_Practicas_y_Consideraciones\" >Best Practices and Considerations<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Rendimiento\" >Performance<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Compatibilidad_con_Navegadores\" >Browser Compatibility<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Uso_en_Frameworks_Modernos\" >Use in Modern Frameworks<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/nelkodev.com\/en\/blog\/mastering-the-for-of-loop-in-javascript\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Introduccion_al_Bucle_for%E2%80%A6of\"><\/span>Introduction to the for\u2026of Loop<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Loop <code>for...of<\/code> was introduced in ES6 (ECMAScript 2015) and provides a simple and direct way to iterable data structures such as Array, Map, Set or even Strings. Unlike other traditional loops, <code>for...of<\/code> It focuses on property values and not indexes, making it ideal for operations where the order and value of elements are important.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"%C2%BFQue_hace_especial_al_for%E2%80%A6of\"><\/span>What makes for\u2026of special?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><code>for...of<\/code> simplifies the code used to iterate over collections of data. Before ES6, the loop <code>for<\/code> classic and <code>forEach<\/code> were the predominant options, but both have their disadvantages. The classic for loop can be verbose and prone to index errors, while <code>forEach<\/code> has limitations regarding the use of instructions such as <code>break<\/code>, <code>continue<\/code>, and <code>return<\/code>.<\/p>\n<p>By contrast, <code>for...of<\/code> combines simplicity and readability, allowing us to interact with each element of the collection directly.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Sintaxis_Basica_del_Bucle_for%E2%80%A6of\"><\/span>Basic Syntax of the for\u2026of Loop<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<pre><code class=\"&quot;language-javascript&quot;\">for (const element of iterable) { \/\/ Code to execute for each element }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Ejemplo_Basico\"><\/span>Basic Example:<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<pre><code class=\"&quot;language-javascript&quot;\">let fruits = [&#039;apple&#039;, &#039;banana&#039;, &#039;cherry&#039;]; for (const fruit of fruits) { console.log(fruit); }<\/code><\/pre>\n<p>This code will print in console:<\/p>\n<pre><code>apple banana cherry<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Trabajando_con_Colecciones_Iterables\"><\/span>Working with Iterable Collections<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Arrays_y_NodeList\"><\/span>Arrays and NodeList<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Arrays in JavaScript are perhaps the most common data structure to use with <code>for...of<\/code>. However, it can also be used with NodeList, which is often obtained through methods like <code>document.querySelectorAll<\/code>.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Ejemplo_con_Arrays\"><\/span>Example with Arrays:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<pre><code class=\"&quot;language-javascript&quot;\">let numbers = [1, 2, 3, 4, 5]; for (let number of numbers) { console.log(number * 2); }<\/code><\/pre>\n<h4><span class=\"ez-toc-section\" id=\"Ejemplo_con_NodeList\"><\/span>Example with NodeList:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<pre><code class=\"&quot;language-javascript&quot;\">let paragraphs = document.querySelectorAll(&#039;p&#039;); for (let paragraph of paragraphs) { paragraph.style.fontSize = &#039;18px&#039;; }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Strings\"><\/span>Strings<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>While not a collection in the traditional sense, strings in JavaScript are iterable, and <code>for...of<\/code> can be used to iterate over each character:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">let greeting = &quot;Hello World!&quot;; for (const character of greeting) { console.log(character); }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Objetos_y_la_Interfaz_Iterable\"><\/span>Objects and the Iterable Interface<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Objects in JavaScript are not iterable by default. However, you can implement the iterable interface to make them work with <code>for...of<\/code>. In practice, structures like Map and Set already implement this interface.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Ejemplo_con_Map\"><\/span>Example with Map:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<pre><code class=\"&quot;language-javascript&quot;\">let map = new Map(); map.set(&#039;name&#039;, &#039;Alice&#039;); map.set(&#039;profession&#039;, &#039;Developer&#039;); for (const [key, value] of map) { console.log(`${key}: ${value}`); }<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Control_de_Flujo_y_Desestructuracion\"><\/span>Flow Control and Destructuring<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Uso_de_break_y_continue\"><\/span>Using break and continue<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>inside a loop <code>for...of<\/code>, we can use the instructions <code>break<\/code> y <code>continue<\/code> to control the execution flow:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">for (const number of [1, 2, 3, 4, 5]) { if (number &gt; 3) break; \/\/ We end the loop if the number is greater than 3 if (number % 2 === 0) continue; \/\/ We go to the next number if it is even console.log(number); }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Desestructuracion_en_for%E2%80%A6of\"><\/span>Destructuring in for\u2026of<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Destructuring is another feature of ES6 that is perfectly complemented by <code>for...of<\/code>, especially when iterating collections of objects or arrays of arrays.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Ejemplo_con_Objetos\"><\/span>Example with Objects:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<pre><code class=\"&quot;language-javascript&quot;\">let users = [ { name: &#039;Ana&#039;, age: 25 }, { name: &#039;Juan&#039;, age: 30 }, { name: &#039;Carla&#039;, age: 22 } ]; for (const { name, age } of users) { console.log(`User: ${name}, Age: ${age}`); }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Iteradores_y_el_protocolo_Iterable\"><\/span>Iterators and the Iterable protocol<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In JavaScript, iterators are objects that know how to access elements in a collection, one element at a time, while keeping track of their current position in that collection. The Iterable protocol is what allows a data structure to be looped through. <code>for...of<\/code>.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Creando_objetos_iterables_personalizados\"><\/span>Creating custom iterable objects<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>An iterable can be created by implementing the method <code>[Symbol.iterator]<\/code>, which must return an object with a method <code>next()<\/code>:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">let range = { start: 1, end: 5, [Symbol.iterator]() { return { current: this.start, last: this.end, next() { if (this.current &lt;= this.last) { return { done: false, value: this.current++ }; } else { return { done: true }; } } }; } }; for (let number of range) { console.log(number); }<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Mejores_Practicas_y_Consideraciones\"><\/span>Best Practices and Considerations<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Rendimiento\"><\/span>Performance<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Although <code>for...of<\/code> provides readability and simplicity, there are scenarios where other forms of iteration could be more efficient, especially in situations with critical performance requirements.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Compatibilidad_con_Navegadores\"><\/span>Browser Compatibility<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>It is important to check loop compatibility <code>for...of<\/code> with the range of browsers you want to support. For older browsers that do not support ES6, transpilers such as Babel can be used.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Uso_en_Frameworks_Modernos\"><\/span>Use in Modern Frameworks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In modern frameworks like React or Angular, iteration operations are often handled through their own abstractions and methods (e.g. using <code>.map()<\/code> in JSX for React). Even so, knowing <code>for...of<\/code> It is crucial for manipulating data outside the view layer.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Loop <code>for...of<\/code> is a powerful addition to any JavaScript developer&#039;s toolkit. Its ability to handle iterable data structures simply and efficiently makes it easy to write concise and readable code. Combining <code>for...of<\/code> With other ES6 features such as destructuring and custom iterators, we can write modern, functional code capable of meeting the challenges of contemporary JavaScript programming.<\/p>\n<p>Master the loop <code>for...of<\/code> and understanding the underlying iterator system in JavaScript expands our possibilities and prepares us to tackle complex iteration tasks with ease and confidence. Continue exploring and experimenting with these concepts to hone your skills and take full advantage of JavaScript&#039;s capabilities.<\/p>","protected":false},"excerpt":{"rendered":"<p>El lenguaje de programaci\u00f3n JavaScript es una parte esencial del desarrollo web moderno. Sus estructuras de control de flujo son herramientas fundamentales para cualquier desarrollador. Entre ellas, el bucle for&#8230;of destaca por ser una manera eficiente y moderna de iterar sobre elementos iterables. Este art\u00edculo es una gu\u00eda profunda sobre el uso y las caracter\u00edsticas [&hellip;]<\/p>","protected":false},"author":1,"featured_media":24491,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,2207],"tags":[1679,205,1368,1289,1283,185,2208,101],"class_list":["post-24490","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-nodejs","tag-avanzada","tag-blog","tag-bucle","tag-dominando","tag-forof","tag-javascript","tag-nodejs","tag-programacion"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24490","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=24490"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24490\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/24491"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=24490"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=24490"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=24490"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}