{"id":666,"date":"2024-07-30T19:53:43","date_gmt":"2024-07-30T17:53:43","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=666"},"modified":"2024-07-30T19:53:43","modified_gmt":"2024-07-30T17:53:43","slug":"003-ciclos-loops","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/04-estructuras-de-control-en-javascript\/003-ciclos-loops\/","title":{"rendered":"003. Ciclos (loops)"},"content":{"rendered":"\n<p>En el cap\u00edtulo anterior hab\u00edamos visto las <strong>estructuras de control<\/strong> que nos iban a ayudar a resolver o a trabajar con <strong>condiciones<\/strong>. Ahora vamos a ver las otras <strong>estructuras de control<\/strong> que nos van a ayudar a controlar el flujo de nuestra programaci\u00f3n, y son los <strong>loops,<\/strong> <strong>bucles<\/strong> o <strong>estructuras repetitivas<\/strong>. En los <strong>bucles<\/strong> entra en juego el <strong>incremento<\/strong> o <strong>decremento<\/strong> de alguna <strong>variable<\/strong> que hace cambiar el valor y va a hacer que se repitan las l\u00edneas de c\u00f3digo hasta que la <strong>variable<\/strong> en cuesti\u00f3n que estamos evaluando llegue al valor deseado y entonces se sale del <strong>ciclo<\/strong>.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>En este cap\u00edtulo veremos las estructuras <strong><em>while<\/em><\/strong>, <strong><em>do while<\/em><\/strong>, <strong><em>for<\/em><\/strong>, y nuevas opciones para el <strong><em>for<\/em> <\/strong>que vinieron en <strong>ES6<\/strong>, como son el <strong><em>for in<\/em><\/strong> y el <strong><em>for of<\/em><\/strong>.<\/p>\n\n\n\n<p>En este cap\u00edtulo veremos las siguientes estructuras:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#while\">Bucle while<\/a><\/li>\n\n\n\n<li><a href=\"#dowhile\">Bucle do while<\/a><\/li>\n\n\n\n<li><a href=\"#for\">Bucle for<\/a><\/li>\n\n\n\n<li><a href=\"#forin\">Bucle for in<\/a><\/li>\n\n\n\n<li><a href=\"#forof\">Bucle for of<\/a><\/li>\n<\/ul>\n\n\n\n<p>Las primeras estructuras que vamos a ver son <strong><em>while<\/em> <\/strong>y do <strong><em>while<\/em><\/strong>, que est\u00e1n cayendo en desuso ya que se trata de <strong>estructuras imperativas<\/strong> de <strong>programaci\u00f3n estructurada<\/strong>, y <strong>Javascript<\/strong> cada vez est\u00e1 siendo m\u00e1s un <strong>lenguaje declarativo<\/strong> y al ser <strong>multiparadigma<\/strong>, sobre todo cuando estamos trabajando con <strong>programaci\u00f3n orientada a objetos<\/strong> y <strong>programaci\u00f3n funcional<\/strong>, generalmente nos gusta escribir un c\u00f3digo m\u00e1s declarativo que imperativo, por lo que es importante conocer las estructuras <strong><em>while<\/em> <\/strong>y <strong><em>do while<\/em><\/strong>, pero en la pr\u00e1ctica cada vez se utilizan menos.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"while\">1. Estructura <em>while<\/em><\/h2>\n\n\n\n<p>Veamos la sintaxis de la estructura <strong><em>while<\/em><\/strong>.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; let contador = 0;\n&nbsp; &nbsp; &nbsp; &nbsp; while (contador &lt; 10) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(contador);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contador++;\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"dowhile\">2. Estructura <em>do while<\/em><\/h2>\n\n\n\n<p>Es una variante de <strong><em>while<\/em> <\/strong>que a\u00fan se ve menos que la primera. La estructura es muy parecida a <strong><em>while<\/em><\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; do {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n&nbsp; &nbsp; &nbsp; &nbsp; } while (condition);<\/pre>\n\n\n\n<p>Veamos un ejm.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; let contador2 = 0;\n&nbsp; &nbsp; &nbsp; &nbsp; do {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"do while \" + contador2);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contador2++;\n&nbsp; &nbsp; &nbsp; &nbsp; } while (contador2 &lt; 10);<\/pre>\n\n\n\n<p>La diferencia entre el <strong>bucle <em>while<\/em> <\/strong>y el <strong><em>do while<\/em><\/strong>, es que en la segunda se ejecuta una vez el bloque de c\u00f3digo que pasamos, independientemente de que se cumpla o no la condici\u00f3n, y despu\u00e9s lee la condici\u00f3n, y en el bucle <strong><em>while<\/em> <\/strong>no ocurre \u00e9sto, primero se lee la condici\u00f3n, y si se cumple, se ejecuta el c\u00f3digo. En el bucle <strong><em>do while<\/em><\/strong>, la evaluaci\u00f3n del c\u00f3digo est\u00e1 al final.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"for\">3. Bucle <em>for<\/em><\/h2>\n\n\n\n<p>En <strong>Javascript<\/strong>, el <strong>ciclo<\/strong> o <strong>bucle<\/strong> m\u00e1s utilizado es el <strong>bucle <em>for<\/em><\/strong>, la cual consta de 3 partes:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">  &nbsp; &nbsp; &nbsp; for (<strong>Inicializaci\u00f3n de la variable<\/strong>; <strong>Condici\u00f3n<\/strong>; <strong>Incremento o decremento<\/strong>) {\n           Sentencias que ejecuta el bucle for\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>Veamos un ejm.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; for (let i = 0; i &lt; 10; i++) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(i) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;;\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>Veamos otro ejm para ir familiariz\u00e1ndonos con el bucle <strong><em>for<\/em><\/strong>.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; let numero = [10,20,30,40,50,60,70,80,90,100];\n&nbsp; &nbsp; &nbsp; &nbsp; for (let i = 0; i &lt; numero.length; i++) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(numero[i]);\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">4. Bucles <em>for in y for of<\/em><\/h2>\n\n\n\n<p>Desde <strong>ES6<\/strong> han surgido variantes de <strong><em>for<\/em> <\/strong>como son <strong><em>for in<\/em><\/strong> y <strong><em>for of<\/em><\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"forin\">4.1 Bucle <em>for in<\/em><\/h3>\n\n\n\n<p>Es un <strong>loop<\/strong> que permite recorrer o iterar las <strong>propiedades<\/strong> de un <strong>objeto<\/strong>. Es un <strong><em>for<\/em> <\/strong>especial para <strong>objetos<\/strong>. Lo que nos pide es una <strong>variable<\/strong> que va a representar la propiedad que <strong>queremos<\/strong> imprimir, la cual est\u00e1 dentro de un <strong>objeto<\/strong>. Veamos un ejm.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Bucle for in\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Especial para objetos\n\n&nbsp; &nbsp; &nbsp; &nbsp; const fran = {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nombre: \"Francisco\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; apellido: \"Paredes\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; edad: 51\n&nbsp; &nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; &nbsp; for (const propiedad in fran) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(propiedad);\n  &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>En el siguiente ejm, adem\u00e1s de la <strong>propiedad<\/strong> vamos a mostrar el valor de dicha <strong>propiedad<\/strong>.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Bucle for in\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Especial para objetos\n\n&nbsp; &nbsp; &nbsp; &nbsp; const fran = {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nombre: \"Francisco\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; apellido: \"Paredes\",\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; edad: 51\n&nbsp; &nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; &nbsp; for (const propiedad in fran) {\n  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Key: \" + propiedad + \" \/ Valor: \" + fran[propiedad])\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"forof\">4.2 Bucle <em>for of<\/em><\/h3>\n\n\n\n<p>Es muy parecido a <strong><em>for in<\/em><\/strong>, s\u00f3lo que en vez de utilizar la palabra reservada <strong><em>in<\/em> <\/strong>vamos a utilizar la palabra reservada <strong><em>of<\/em><\/strong>. Nos permite recorrer todos los elementos de cualquier objeto que sea iterable en <strong>Javascript<\/strong>, como <strong>arrays<\/strong>, <strong>strings<\/strong>&#8230;<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; const numeros = [1,2,3,4,5,6,7,8,9,10,20];\n  &nbsp; &nbsp; &nbsp; for (const item of numeros) {\n  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(item);\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>Por lo tanto:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><em>for in<\/em><\/strong> es para objetos.<\/li>\n\n\n\n<li><strong><em>for of<\/em><\/strong> es para <strong>elementos iterables<\/strong> (<strong>arrays<\/strong>, <strong>strings<\/strong>&#8230;).<\/li>\n<\/ul>\n\n\n\n<p><strong>Ejm con for of<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; let cadena = \"Hola mundo\";\n&nbsp; &nbsp; &nbsp; &nbsp; for (const elemento of cadena) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(elemento);\n  &nbsp; &nbsp; &nbsp; }<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>En el cap\u00edtulo anterior hab\u00edamos visto las estructuras de control que nos iban a ayudar a resolver o a trabajar [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":658,"menu_order":2,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-666","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"En el cap\u00edtulo anterior hab\u00edamos visto las estructuras de control que nos iban a ayudar a resolver o a trabajar [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/666","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=666"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/666\/revisions"}],"predecessor-version":[{"id":668,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/666\/revisions\/668"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/658"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=666"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}