{"id":24554,"date":"2024-02-09T18:35:46","date_gmt":"2024-02-09T17:35:46","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/como-usar-foreach-en-javascript-para-iterar-arrays\/"},"modified":"2024-06-03T17:36:20","modified_gmt":"2024-06-03T16:36:20","slug":"como-usar-foreach-en-javascript-para-iterar-arrays","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/","title":{"rendered":"How to Use forEach in JavaScript to Iterate Arrays"},"content":{"rendered":"<p>JavaScript is a programming language widely used in both frontend and backend development. Provides several methods for iterating through arrays, one of which is <code>forEach<\/code>. This method provides a simple and efficient way to execute a function on each element of an array. In this article, we will explore how to use <code>forEach<\/code> in JavaScript to iterate arrays, ensuring that even programming beginners can understand and apply this method in their projects.<\/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\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#%C2%BFQue_es_forEach_en_JavaScript\" >What is forEach in JavaScript?<\/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\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Caracteristicas_de_forEach\" >forEach Features<\/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\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Como_Usar_forEach_para_Iterar_Arrays_en_JavaScript\" >How to Use forEach to Iterate Arrays in JavaScript<\/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\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Parametros_de_la_funcion_callback\" >Callback function parameters<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Valor_de_retorno\" >Return value<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Ejemplos_de_Uso_de_forEach_en_JavaScript\" >Examples of Using forEach in JavaScript<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Iteracion_Simple\" >Simple Iteration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Acceso_al_Indice_y_al_Array\" >Access to the Index and Array<\/a><\/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\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Modificacion_del_Array_Original\" >Modification of the Original Array<\/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\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Uso_de_forEach_con_Arrays_de_Objetos\" >Using forEach with Object Arrays<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Buenas_Practicas_y_Consideraciones_al_Usar_forEach\" >Good Practices and Considerations When Using forEach<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Eficiencia\" >Efficiency<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#forEach_vs_for_Loop\" >forEach vs for Loop<\/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\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Uso_de_thisArg\" >Using thisArg<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Asincronia_en_forEach\" >Asynchrony in forEach<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/nelkodev.com\/en\/blog\/how-to-use-foreach-in-javascript-to-iterate-arrays\/#Resumen\" >Summary<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"%C2%BFQue_es_forEach_en_JavaScript\"><\/span>What is forEach in JavaScript?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The method <code>forEach<\/code> JavaScript is a higher-order function included in the Array prototype that is designed to simplify looping through arrays. Instead of using traditional loops like <code>for<\/code> o <code>while<\/code>, <code>forEach<\/code> allows you to execute a callback function for each element of the array.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Caracteristicas_de_forEach\"><\/span>forEach Features<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ul>\n<li><strong>Clear syntax:<\/strong> <code>forEach<\/code> provides a more readable syntax compared to traditional loops.<\/li>\n<li><strong>Callback function:<\/strong> The function passed to <code>forEach<\/code> It is executed once for each element of the array.<\/li>\n<li><strong>It does not modify the original array:<\/strong> <code>forEach<\/code> It does not alter the array on which it is invoked, although the callback function can do so.<\/li>\n<li><strong>It has functional scope (scope):<\/strong> The callback function can access the index of the current element, the element itself, and the entire array.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Como_Usar_forEach_para_Iterar_Arrays_en_JavaScript\"><\/span>How to use <code>forEach<\/code> to Iterate Arrays in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>To use <code>forEach<\/code>, you simply need to have an array and a function that you want to apply to each of its elements. Let&#039;s see an example of its use:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const fruits = [&#039;apple&#039;, &#039;banana&#039;, &#039;cherry&#039;]; fruits.forEach(function(item, index, array) { console.log(item, index); });<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Parametros_de_la_funcion_callback\"><\/span>Callback function parameters<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ol>\n<li><strong>Current item:<\/strong> It is the element of the array that is being processed.<\/li>\n<li><strong>Index (optional):<\/strong> It is the index of the current element in the array.<\/li>\n<li><strong>Array (optional):<\/strong> It is the array that <code>forEach<\/code> is traveling.<\/li>\n<\/ol>\n<h3><span class=\"ez-toc-section\" id=\"Valor_de_retorno\"><\/span>Return value<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Notably <code>forEach<\/code> It does not return any value, its use is merely to execute an operation for each element of the array.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Ejemplos_de_Uso_de_forEach_en_JavaScript\"><\/span>Examples of Use of <code>forEach<\/code> in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Iteracion_Simple\"><\/span>Simple Iteration<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Suppose you want to print the name of each fruit in your array in the console:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const fruits = [&#039;apple&#039;, &#039;banana&#039;, &#039;cherry&#039;]; fruits.forEach(fruit =&gt; { console.log(fruit); });<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Acceso_al_Indice_y_al_Array\"><\/span>Access to the Index and Array<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Maybe you not only want the element, but also know its position:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const fruits = [&#039;apple&#039;, &#039;banana&#039;, &#039;cherry&#039;]; fruits.forEach((fruit, index) =&gt; { console.log(`Fruit ${fruit} is at position ${index}`); });<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Modificacion_del_Array_Original\"><\/span>Modification of the Original Array<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>If you want to modify the array while iterating over it, you can do so directly:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const numbers = [1, 2, 3, 4]; numbers.forEach((number, index, arr) =&gt; { arr[index] = number * 2; }); console.log(numbers); \/\/ [2, 4, 6, 8]<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Uso_de_forEach_con_Arrays_de_Objetos\"><\/span>Use of <code>forEach<\/code> with Arrays of Objects<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In an array of objects, <code>forEach<\/code> It can be very useful to execute an action on each object:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const books = [ { title: &quot;The Hobbit&quot;, author: &quot;JRR Tolkien&quot; }, { title: &quot;1984&quot;, author: &quot;George Orwell&quot; } ]; books.forEach(book =&gt; { console.log(`${book.title} was written by ${book.author}`); });<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Buenas_Practicas_y_Consideraciones_al_Usar_forEach\"><\/span>Good Practices and Considerations when Using <code>forEach<\/code><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Eficiencia\"><\/span>Efficiency<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Although <code>forEach<\/code> is very practical, it is not always the most efficient option for iterating arrays, especially if you need to break the loop, since <code>forEach<\/code> cannot be terminated ahead of time with <code>break<\/code> o <code>return<\/code>.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"forEach_vs_for_Loop\"><\/span><code>forEach<\/code> vs <code>for<\/code> Loop<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Compared to a loop <code>for<\/code>, <code>forEach<\/code> may be more elegant and easier to read, but a loop <code>for<\/code> can offer more control and be faster in certain scenarios.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Uso_de_thisArg\"><\/span>Use of <code>thisArg<\/code><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><code>forEach<\/code> accepts an optional second parameter <code>thisArg<\/code>, which you can use to pass a context <code>Este<\/code> to your callback function:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const title = { text: &#039;The title text is: &#039; }; const fruits = [&#039;apple&#039;, &#039;banana&#039;, &#039;cherry&#039;]; fruits.forEach(function(fruit) { console.log(this.text + fruit); }, title);<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Asincronia_en_forEach\"><\/span>Asynchrony in <code>forEach<\/code><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><code>forEach<\/code> He doesn&#039;t wait for promises. So if you need to perform asynchronous operations within a <code>forEach<\/code>, you should use <code>async\/await<\/code> with alternative methods, such as <code>for...of<\/code>.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Resumen\"><\/span>Summary<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><code>forEach<\/code> is a convenient and expressive method for iterating through arrays in JavaScript. It is easy to use and can make code cleaner and easier to read. However, keep in mind the limitations and scenarios in which other iteration methods, such as <code>for<\/code>, <code>for...of<\/code>, <code>map<\/code>, either <code>reduces<\/code>, may be more suitable.<\/p>\n<p>Through this article, we have not only learned how <code>forEach<\/code> can be used to improve our code when iterating arrays in JavaScript, but we have also seen different practical ways to implement <code>forEach<\/code> in a variety of situations.<\/p>\n<p>Now that you have a solid understanding of how it works <code>forEach<\/code> and when to use it, you can incorporate this method into your JavaScript projects to manipulate arrays in a more efficient and elegant way. Always remember to consider the nature of the task at hand to determine if <code>forEach<\/code> is the best option and enjoy writing cleaner and more maintainable code.<\/p>","protected":false},"excerpt":{"rendered":"<p>JavaScript es un lenguaje de programaci\u00f3n ampliamente utilizado tanto en el desarrollo de frontend como en el de backend. Ofrece varios m\u00e9todos para iterar a trav\u00e9s de arrays, uno de los cuales es forEach. Este m\u00e9todo proporciona una forma sencilla y eficiente de ejecutar una funci\u00f3n en cada elemento de un array. En este art\u00edculo, [&hellip;]<\/p>","protected":false},"author":1,"featured_media":24555,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420],"tags":[38,584,205,1279,1734,1412,185,60,168,1461,79],"class_list":["post-24554","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-como","tag-arrays","tag-blog","tag-foreach","tag-guias","tag-iterar","tag-javascript","tag-para","tag-practicas","tag-tutoriales","tag-usar"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24554","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=24554"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24554\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/24555"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=24554"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=24554"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=24554"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}