<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="es"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://recursivos.com/feed.xml" rel="self" type="application/atom+xml"/><link href="https://recursivos.com/" rel="alternate" type="text/html" hreflang="es"/><updated>2026-03-10T22:55:47+00:00</updated><id>https://recursivos.com/feed.xml</id><title type="html">Recursivos</title><entry><title type="html">Bucle ‘for’ - Curso de JS</title><link href="https://recursivos.com/js/bucle-for/" rel="alternate" type="text/html" title="Bucle &apos;for&apos; - Curso de JS"/><published>2025-12-03T00:00:00+00:00</published><updated>2025-12-03T00:00:00+00:00</updated><id>https://recursivos.com/js/bucle-for</id><content type="html" xml:base="https://recursivos.com/js/bucle-for/">&lt;p&gt;La instrucción &lt;strong&gt;for&lt;/strong&gt; es una estructura de control que permite &lt;strong&gt;crear bucles de forma controlada&lt;/strong&gt;, por lo que es una herramienta muy utilizada en JavaScript. Su uso facilita la repetición de código tantas veces como sea necesario, hasta que la condición especificada se evalúe como falsa.&lt;/p&gt; &lt;p&gt;A diferencia del &lt;a href=&quot;/js/bucle-while/&quot;&gt;bucle ‘while’&lt;/a&gt;, que suele utilizarse cuando no se conoce el número de repeticiones necesarias, el bucle &lt;strong&gt;for&lt;/strong&gt; es la opción habitual cuando el &lt;strong&gt;número de iteraciones es fijo&lt;/strong&gt; y conocido o fácilmente controlable. Por ejemplo, puede usarse para recorrer un rango definido de números, recorrer los índices de un &lt;em&gt;array&lt;/em&gt;, crear estructuras repetitivas o acumular cálculos que requieren varios pasos.&lt;/p&gt; &lt;p class=&quot;notice-info&quot;&gt;Existen otras variantes más específicas de bucles controlados: &lt;strong&gt;for…of&lt;/strong&gt; se utiliza para crear bucles sobre &lt;em&gt;arrays&lt;/em&gt;, mientras que &lt;strong&gt;for…in&lt;/strong&gt; permite trabajar con bucles relacionados con las propiedades de objetos.&lt;/p&gt; &lt;h2 id=&quot;estructura&quot;&gt;Estructura&lt;/h2&gt; &lt;p&gt;La estructura de los &lt;strong&gt;bucles for&lt;/strong&gt; integra tres expresiones en su encabezado (inicialización, condición y actualización), lo que lo hacen compacto y flexible, aunque puede resultar algo complejo para quien empieza a programar. Tras el encabezado se encuentra el cuerpo, que contiene el código a repetir.&lt;/p&gt; &lt;p&gt;Veamos detalladamente el propósito de estas expresiones:&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Inicialización&lt;/strong&gt;: es la expresión que se ejecuta una sola vez, antes de que comience el bucle. Se utiliza para declarar o asignar una variable de control, como sería un contador. Con esta variable indicamos el valor inicial del bucle.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Condición&lt;/strong&gt;: es una expresión booleana que se evalúa al inicio de cada iteración. Comprueba si la condición es verdadera. Si es verdadera, se ejecuta el código indicado en el bucle. En caso contrario, el bucle termina. La condición indicada será evaluada al inicio de cada nueva iteración.&lt;/p&gt; &lt;p class=&quot;notice-info&quot;&gt;Si se omite la condición, se considera siempre verdadera. Esto podría producir un bucle infinito si no se controla de otra manera.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Actualización&lt;/strong&gt;: es la expresión que se ejecuta al finalizar cada iteración, justo después de ejecutar el código del cuerpo del bucle. Se utiliza para modificar (incrementar o disminuir) el valor de la variable de control.&lt;/p&gt; &lt;p&gt;Cualquiera de estas tres expresiones del encabezado del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; son &lt;strong&gt;opcionales&lt;/strong&gt;, por lo que pueden omitirse. Lo único que no puede omitirse son los punto y coma (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;;&lt;/code&gt;) que permiten delimitar su posición. Así podemos construir bucles muy flexibles, como los bucles infinitos controlados de forma manual.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(;;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Bucle infinito&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;algoritmo&quot;&gt;Algoritmo&lt;/h2&gt; &lt;p&gt;El &lt;strong&gt;algoritmo del bucle for&lt;/strong&gt; sigue un orden de ejecución muy concreto. En primer lugar se ejecuta la expresión de «inicialización», que se evalúa una sola vez antes de que comience el bucle y permite declarar la variable de control.&lt;/p&gt; &lt;p&gt;A continuación se evalúa la «condición»: si el resultado es verdadero, se inicia la primera iteración; pero si es falso, el bucle finaliza de forma inmediata sin ejecutar el código del cuerpo. La condición se verifica en cada iteración.&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-for.svg&quot; alt=&quot;Diagrama de flujo de un bucle &apos;for&apos;&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un bucle &apos;for&apos;.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;Cuando se ejecuta el cuerpo del bucle, JS evalúa la expresión de «actualización», cuya función habitual es modificar la variable de control (incrementándola o disminuyéndola), para avanzar hacia la finalización del bucle.&lt;/p&gt; &lt;p&gt;Tras la actualización, el flujo de control del programa regresa al punto de evaluación de la «condición». Este ciclo se repite tantas veces como sea necesario, hasta que la condición inicial resulte falsa. Entonces, el bucle habrá terminado.&lt;/p&gt; &lt;h2 id=&quot;sintaxis&quot;&gt;Sintaxis&lt;/h2&gt; &lt;p&gt;La &lt;strong&gt;sintaxis del bucle for&lt;/strong&gt; es compacta y bien definida. Comienza con la palabra reservada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; y, entre paréntesis &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;()&lt;/code&gt;, se indican las tres expresiones que controlan el bucle, separadas con un punto y coma (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;;&lt;/code&gt;).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;inicialización&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;actualización&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si la condición es true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Tras el encabezado se coloca el &lt;strong&gt;cuerpo del bucle&lt;/strong&gt;, delimitado por llaves &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{}&lt;/code&gt;. El cuerpo contiene las sentencias que se ejecutarán en cada iteración. Si el cuerpo consta de una sola instrucción, las llaves pueden omitirse, aunque si se incluyen se mejora significativamente la legibilidad del código.&lt;/p&gt; &lt;h2 id=&quot;ejemplo-contador-numérico&quot;&gt;Ejemplo: contador numérico&lt;/h2&gt; &lt;p&gt;Un ejemplo sencillo para comprender cómo funciona el bucle &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; es crear un contador. Para ello, se inicializa la &lt;strong&gt;variable de control&lt;/strong&gt; con un valor inicial: en este caso, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;; se define una &lt;strong&gt;condición&lt;/strong&gt; que debe cumplirse: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i &amp;lt; 5&lt;/code&gt; (&lt;var&gt;i&lt;/var&gt; es menor que 5); y se indica una &lt;strong&gt;actualización&lt;/strong&gt; que incrementa el contador en cada iteración: el operador aritmético &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i++&lt;/code&gt;, equivalente a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i = i + 1&lt;/code&gt;.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Iteración:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Como la expresión de inicialización establece &lt;var&gt;i&lt;/var&gt; en 1, el primer mensaje mostrado corresponde a ese valor. El bucle sigue ejecutándose mientras la condición sea verdadera, por lo que se realizan &lt;strong&gt;cuatro iteraciones&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;Este es el resultado:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Iteración: 1&lt;br /&gt; Iteración: 2&lt;br /&gt; Iteración: 3&lt;br /&gt; Iteración: 4&lt;/p&gt; &lt;/blockquote&gt; &lt;h2 id=&quot;saltar-una-iteración&quot;&gt;Saltar una iteración&lt;/h2&gt; &lt;p&gt;La instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;continue&lt;/code&gt; permite &lt;strong&gt;saltar una iteración del bucle&lt;/strong&gt; para ir de forma directa hacia la iteración siguiente. Esta funcionalidad puede ser muy útil cuando se necesita crear excepciones dentro de un bucle.&lt;/p&gt; &lt;p&gt;Por ejemplo, vamos a esquivar la tercera iteración:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Iteración:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;Cuando la variable &lt;var&gt;i&lt;/var&gt; vale 3, se ejecuta la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;continue&lt;/code&gt;, con lo cual, el flujo del programa salta hasta la siguiente iteración.&lt;/p&gt; &lt;p&gt;Resultado:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Iteración: 1&lt;br /&gt; Iteración: 2&lt;br /&gt; Iteración: 4&lt;/p&gt; &lt;/blockquote&gt; &lt;h2 id=&quot;interrumpir-el-bucle&quot;&gt;Interrumpir el bucle&lt;/h2&gt; &lt;p&gt;La instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt; permite interrumpir el bucle en la iteración actual, siempre que se cumpla una condición determinada. Su utilidad radica en la necesidad de terminar el bucle de forma excepcional.&lt;/p&gt; &lt;p&gt;Vamos a terminar el bucle en la tercera iteración:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Iteración:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;Cuando la variable &lt;var&gt;i&lt;/var&gt; vale 3, se ejecuta la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt;. En este momento, el bucle termina antes de imprimir la tercera iteración.&lt;/p&gt; &lt;p&gt;Resultado:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Iteración: 1&lt;br /&gt; Iteración: 2&lt;/p&gt; &lt;/blockquote&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">La instrucción for es una estructura de control que permite crear bucles de forma controlada, por lo que es una herramienta muy utilizada en JavaScript. Su uso facilita la repetición de código tantas veces como sea necesario, hasta que la condición especificada se evalúe como falsa.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Bucle ‘while’ y ‘do…while’ - Curso de JS</title><link href="https://recursivos.com/js/bucle-while/" rel="alternate" type="text/html" title="Bucle &apos;while&apos; y &apos;do...while&apos; - Curso de JS"/><published>2025-11-02T00:00:00+00:00</published><updated>2025-11-02T00:00:00+00:00</updated><id>https://recursivos.com/js/bucle-while</id><content type="html" xml:base="https://recursivos.com/js/bucle-while/">&lt;p&gt;La instrucción &lt;strong&gt;while&lt;/strong&gt; del lenguaje JavaScript es una estructura de control que permite &lt;strong&gt;crear bucles&lt;/strong&gt;. Está diseñada para repetir un bloque de código mientras se cumpla una condición evaluada como verdadera (&lt;em&gt;truthy&lt;/em&gt;). Se trata de una herramienta flexible, pero debe usarse con cuidado para evitar los bucles infinitos.&lt;/p&gt; &lt;p&gt;Su propósito principal es permitir la iteración indefinida, es decir, repetir una tarea un número desconocido de veces hasta que la condición deje de ser verdadera. Por tanto, a diferencia del &lt;a href=&quot;/js/bucle-for/&quot;&gt;bucle ‘for’&lt;/a&gt;, que suelen usarse cuando se conoce el número de iteraciones necesarias, el bucle &lt;strong&gt;while&lt;/strong&gt; resulta ideal para &lt;strong&gt;cuando se desconoce cuántas repeticiones harán falta&lt;/strong&gt; para llegar al final.&lt;/p&gt; &lt;p&gt;En JavaScript existen dos variantes de bucles basados en esta idea. El bucle &lt;strong&gt;while&lt;/strong&gt;, por defecto, evalúa la condición antes de cada iteración. Si la condición es verdadera, ejecuta el bloque de código; si es falsa, el bucle termina.&lt;/p&gt; &lt;p&gt;En cambio, la instrucción &lt;strong&gt;do…while&lt;/strong&gt; funciona diferente: ejecuta el bloque al menos una vez antes de evaluar la condición. Si dicha condición es verdadera, vuelve a ejecutar el código, y así sucesivamente hasta que se vuelva falsa.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;/js/bucle-while/#while&quot;&gt;Instrucción &lt;strong&gt;while&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;/js/bucle-while/#do-while&quot;&gt;Instrucción &lt;strong&gt;do…while&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h2 id=&quot;while&quot;&gt;La instrucción ‘while’&lt;/h2&gt; &lt;p&gt;La instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt; permite crear bucles &lt;strong&gt;controlados por entrada&lt;/strong&gt;, es decir, que primero comprueba si la condición establecida es válida. Luego, entra en el cuerpo del bucle para ejecutar el bloque de código.&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-while.svg&quot; alt=&quot;Diagrama de flujo de un bucle &apos;while&apos;&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un bucle &apos;while&apos;.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;Como podemos ver en este diagrama de flujo, el bucle se ejecutará repetidamente y de forma indefinida siempre que la condición sea &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadera). El bucle no terminará hasta que la condición sea &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falsa).&lt;/p&gt; &lt;p&gt;La sintaxis de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt; es la siguiente:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si la condición es true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Entre paréntesis &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;()&lt;/code&gt; se indica la condición a evaluar. Puede ser una expresión lógica, aritmética, comparativa o booleana. Las llaves &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{}&lt;/code&gt; que delimitan el bloque contienen el código a ejecutar mientras la condición devuelva &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Iteración:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;En este ejemplo, primero declaramos la variable &lt;var&gt;contador&lt;/var&gt; y la inicializamos en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;. En la condición del bucle se especifica que su valor debe ser menor o igual que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;. Luego, dentro del bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt; incrementamos la variable en una unidad para preparar la siguiente iteración; así evitamos un bucle infinito.&lt;/p&gt; &lt;p&gt;Resultado:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Iteración: 1&lt;br /&gt; Iteración: 2&lt;br /&gt; Iteración: 3&lt;br /&gt; Iteración: 4&lt;br /&gt; Iteración: 5&lt;br /&gt;&lt;/p&gt; &lt;/blockquote&gt; &lt;p class=&quot;notice-info&quot;&gt;En la última iteración, el valor de la variable &lt;var&gt;contador&lt;/var&gt; pasó a ser &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;6&lt;/code&gt;. Al evaluarse nuevamente la condición, esta dejó de ser verdadera, por lo que el bucle finalizó y ya no se imprimió ningún valor adicional.&lt;/p&gt; &lt;h2 id=&quot;do-while&quot;&gt;La instrucción ‘do…while’&lt;/h2&gt; &lt;p&gt;La instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;do...while&lt;/code&gt; permite crear bucles &lt;strong&gt;controlados por salida&lt;/strong&gt;. En este caso, primero se ejecuta el bloque de código del bucle, antes de verificar la condición. Tras completar la primera iteración, se verifica la condición.&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-do-while.svg&quot; alt=&quot;Diagrama de flujo de un bucle &apos;do...while&apos;&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un bucle &apos;do...while&apos;.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;Este tipo de bucle también seguirá ejecutándose mientras la condición sea verdadera. Pero a diferencia del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt;, se garantiza que el código se ejecuta al menos una vez. El bucle termina cuando la condición deja de cumplirse.&lt;/p&gt; &lt;p&gt;Esta es la sintaxis de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;do...while&lt;/code&gt;:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// como mínimo una vez&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;La palabra reservada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;do&lt;/code&gt; inicia el bucle, y dentro de las llaves &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{}&lt;/code&gt; se coloca el código que se ejecutará al menos una vez. Tras cerrar el bloque de código se especifica la palabra reservada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt;. Después del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt;, entre paréntesis &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;()&lt;/code&gt;, se indica la condición a evaluar al final de cada iteración.&lt;/p&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Iteración:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;En este ejemplo, tras declarar la variable &lt;var&gt;contador&lt;/var&gt; se ejecuta una primera iteración sin evaluar la condición. Se incrementa el valor de la variable en una unidad. Después se verifica que la variable sea menor o igual que &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;Resultado:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Iteración: 1&lt;br /&gt; Iteración: 2&lt;br /&gt; Iteración: 3&lt;br /&gt; Iteración: 4&lt;br /&gt; Iteración: 5&lt;br /&gt;&lt;/p&gt; &lt;/blockquote&gt; &lt;p class=&quot;notice-info&quot;&gt;Obtenemos el mismo resultado que en el ejemplo con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt;, pero con una diferencia: el código se ejecutará siempre la primera vez. Por ejemplo, si el contador empezara en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt;, el resultado sería «Iteración: 7».&lt;/p&gt; &lt;h2 id=&quot;esquivar-iteraciones&quot;&gt;Esquivar iteraciones&lt;/h2&gt; &lt;p&gt;Mediante el uso de la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;continue&lt;/code&gt; es posible omitir la ejecución de una iteración concreta, saltando directamente a la siguiente iteración. En un bucle &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt;, el programa comprobará de nuevo la condición del bucle.&lt;/p&gt; &lt;p&gt;Vamos a esquivar la tercera iteración:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Iteración:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;Cuando la variable &lt;var&gt;contador&lt;/var&gt; vale 3, se ejecuta la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;continue&lt;/code&gt;, por lo que el resto del bucle se omite y se pasa a la iteración siguiente.&lt;/p&gt; &lt;p&gt;Resultado:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Iteración: 1&lt;br /&gt; Iteración: 2&lt;br /&gt; Iteración: 4&lt;br /&gt; Iteración: 5&lt;br /&gt;&lt;/p&gt; &lt;/blockquote&gt; &lt;h2 id=&quot;interrupción-de-bucles&quot;&gt;Interrupción de bucles&lt;/h2&gt; &lt;p&gt;Si por el contrario, queremos que el bucle &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt; finalice de forma inmediata en la iteración actual, se puede usar la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt;. También se utiliza si se quiere abandonar el bucle al cumplirse una condición excepcional y concreta.&lt;/p&gt; &lt;p&gt;Vamos a interrumpirlo en la tercera iteración:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Iteración:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;contador&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este caso, cuando &lt;var&gt;contador&lt;/var&gt; vale 3 se ejecuta la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt;, deteniendo el bucle sin completar más iteraciones.&lt;/p&gt; &lt;p&gt;Ahora ya solo imprime:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Iteración: 1&lt;br /&gt; Iteración: 2&lt;br /&gt;&lt;/p&gt; &lt;/blockquote&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">La instrucción while del lenguaje JavaScript es una estructura de control que permite crear bucles. Está diseñada para repetir un bloque de código mientras se cumpla una condición evaluada como verdadera (truthy). Se trata de una herramienta flexible, pero debe usarse con cuidado para evitar los bucles infinitos.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Operador condicional (ternario) - Curso de JS</title><link href="https://recursivos.com/js/operador-condicional/" rel="alternate" type="text/html" title="Operador condicional (ternario) - Curso de JS"/><published>2025-11-01T00:00:00+00:00</published><updated>2025-11-01T00:00:00+00:00</updated><id>https://recursivos.com/js/operador-condicional</id><content type="html" xml:base="https://recursivos.com/js/operador-condicional/">&lt;p&gt;El &lt;strong&gt;operador condicional (ternario)&lt;/strong&gt; constituye una forma compacta, concisa y elegante de escribir una sentencia condicional del tipo &lt;a href=&quot;/js/condicional-if-else/&quot;&gt;if…else&lt;/a&gt;, pero &lt;strong&gt;en una sola línea&lt;/strong&gt;. De hecho, es conocido como operador «ternario» porque es el único operador del lenguaje JavaScript que usa tres operandos para funcionar. Se expresa con dos símbolos: el de interrogación (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;?&lt;/code&gt;) y los dos puntos (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:&lt;/code&gt;).&lt;/p&gt; &lt;p&gt;Mientras que la instrucción &lt;strong&gt;if…else&lt;/strong&gt; se utiliza para ejecutar bloques de código con múltiples sentencias y manejar lógica más compleja, el operador ternario (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;? :&lt;/code&gt;) se usa principalmente cuando se necesita evaluar una condición y devolver un valor de forma directa, ideal para expresiones simples y de una sola línea.&lt;/p&gt; &lt;h2 id=&quot;sintaxis&quot;&gt;Sintaxis&lt;/h2&gt; &lt;p&gt;Como su propio nombre sugiere, la sintaxis del operador ternario está compuesta por tres partes, ya que usa tres operandos. La primera parte es una condición, seguida de un signo de interrogación (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;?&lt;/code&gt;). Le sigue una expresión para ejecutar cuando la condición sea verdadera, seguida de los dos puntos (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:&lt;/code&gt;). Finalmente, se indica la expresión a ejecutar si la condición es falsa.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;exprSiTrue&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;exprSiFalse&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;La &lt;strong&gt;condición&lt;/strong&gt; es una expresión booleana, es decir, algo que puede evaluarse como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero) o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso). Por ejemplo, una comparación (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;edad &amp;gt;= 30&lt;/code&gt;) o una verificación de igualdad (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;usuario === &apos;admin&apos;&lt;/code&gt;).&lt;/p&gt; &lt;p&gt;La &lt;strong&gt;expresión verdadera&lt;/strong&gt; es la parte del operador ternario que se ejecuta solo si la condición inicial se cumple (verdadera). Puede ser cualquier expresión válida del lenguaje JavaScript, como sería un valor literal, una llamada a función, una operación matemática o incluso otra expresión condicional.&lt;/p&gt; &lt;p&gt;Por su parte, la &lt;strong&gt;expresión falsa&lt;/strong&gt; define el resultado alternativo, es decir, lo que se devuelve cuando la condición no se cumple (falsa). Aunque no es obligatorio, es una buena práctica que ambas expresiones devuelvan valores del mismo tipo o con un propósito equivalente, para mantener la coherencia del código.&lt;/p&gt; &lt;h3 id=&quot;ejemplo-básico&quot;&gt;Ejemplo básico&lt;/h3&gt; &lt;p&gt;Vamos a crear un ejemplo en el que se asigna un valor monetario a la variable &lt;var&gt;precioEnvio&lt;/var&gt; para decidir el precio de envío de un paquete. Si el usuario es miembro, el precio de envío vale 0,00 €, pero si no es miembro, vale 4,95 €.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;esMiembro&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;precioEnvio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;esMiembro&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;4.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;El precio de envío es:&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;precioEnvio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;La constante &lt;var&gt;esMiembro&lt;/var&gt; es verdadera, por tanto, se le asigna el precio de 0,00 €. Si fuese falsa, se le aplicaría el precio de 4,95 €. Como se puede ver, el valor se asigna en la misma declaración de la variable &lt;var&gt;precioEnvio&lt;/var&gt;.&lt;/p&gt; &lt;p&gt;Este código tan simple y compacto es equivalente al siguiente, que usa la instrucción condicional ‘if…else’ en lugar del operador condicional ternario:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;esMiembro&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;precioEnvio&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;esMiembro&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;precioEnvio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;precioEnvio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;4.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;En este caso, el código es más extenso y algo repetitivo, ya que requiere realizar dos asignaciones por separado. Sin embargo, al tener dos bloques de código independientes, resultaría útil si se tuviera que añadir más sentencias o realizar operaciones adicionales en cada rama del condicional.&lt;/p&gt; &lt;h2 id=&quot;anidación&quot;&gt;Anidación&lt;/h2&gt; &lt;p&gt;Los operadores ternarios pueden anidarse de manera encadenada, de forma similar a la que se consigue mediante un ‘if…else if…else’. No obstante, no se recomienda abusar de esta técnica porque reduce la legibilidad del código.&lt;/p&gt; &lt;p&gt;La sintaxis es la siguiente:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nx&quot;&gt;condición1&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;valor1&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;condición2&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;valor2&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;condición3&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;valor3&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;valor4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;Para mejorar la legibilidad, el código se puede dividir en varias líneas sin que esto afecte a su funcionamiento. Si se deja todo en una misma línea, el resultado será una instrucción larga y difícil de leer.&lt;/p&gt; &lt;p&gt;El operador ternario se evalúa de izquierda a derecha. Si la primera condición es falsa, pasa a la expresión de la derecha, después de los dos puntos (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:&lt;/code&gt;). Entonces, el operando de la derecha del todo se convierte en otro operador ternario, y así sucesivamente tantas veces como sea necesario.&lt;/p&gt; &lt;h3 id=&quot;ejemplo-de-anidación&quot;&gt;Ejemplo de anidación&lt;/h3&gt; &lt;p&gt;Para “ilustrar” esta estructura de código, vamos a crear un pequeño programa que analice una nota de examen y muestre la calificación textual: «suspendido» (&amp;lt; 5), «aprobado» (&amp;lt; 7), «notable» (&amp;lt; 9) o «sobresaliente».&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;calificacion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Suspendido&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Aprobado&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Notable&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Excelente&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;calificacion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, primero se evalúa la expresión &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nota &amp;lt; 5&lt;/code&gt;. Como la variable &lt;var&gt;nota&lt;/var&gt; vale 7, la condición es falsa, por lo que el flujo pasa al siguiente ternario. Luego se evalúa la expresión &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nota &amp;lt; 7&lt;/code&gt;, que también es falsa. En este punto, la expresión a evaluar es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nota &amp;lt; 9&lt;/code&gt;; ahora la condición es verdadera, por lo tanto, se asigna el valor «Notable» a la variable &lt;var&gt;calificacion&lt;/var&gt;.&lt;/p&gt; &lt;p&gt;Aunque este ejemplo funciona correctamente, no se recomienda anidar operadores ternarios más allá de dos o tres condiciones, ya que dificulta la legibilidad y el mantenimiento del código, sobre todo para otros programadores. Para más de tres condiciones, es preferible utilizar la estructura &lt;a href=&quot;/js/condicional-switch/&quot;&gt;switch&lt;/a&gt;.&lt;/p&gt; &lt;h2 id=&quot;consejos&quot;&gt;Consejos&lt;/h2&gt; &lt;p&gt;Usa el operador condicional ternario cuando la condición sea simple o cuando ambas ramas devuelvan valores claros y breves. También es útil usarlo es cuando se quiere mantener un código más compacto y conciso.&lt;/p&gt; &lt;p&gt;Por el contrario, evita emplearlo cuando las operaciones sean demasiado largas o complejas, ya que esto solo añadiría complejidad a su su legibilidad. Tampoco conviene abusar de las anidaciones de ternarios.&lt;/p&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">El operador condicional (ternario) constituye una forma compacta, concisa y elegante de escribir una sentencia condicional del tipo if…else, pero en una sola línea. De hecho, es conocido como operador «ternario» porque es el único operador del lenguaje JavaScript que usa tres operandos para funcionar. Se expresa con dos símbolos: el de interrogación (?) y los dos puntos (:).</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Condicional ‘switch’ - Curso de JS</title><link href="https://recursivos.com/js/condicional-switch/" rel="alternate" type="text/html" title="Condicional &apos;switch&apos; - Curso de JS"/><published>2025-10-18T00:00:00+00:00</published><updated>2025-10-18T00:00:00+00:00</updated><id>https://recursivos.com/js/condicional-switch</id><content type="html" xml:base="https://recursivos.com/js/condicional-switch/">&lt;p&gt;El condicional &lt;strong&gt;switch&lt;/strong&gt; es una instrucción que permite evaluar una expresión y ejecutar diferentes bloques de código según el valor obtenido. Resulta útil cuando se puede tener varios valores posibles, ya que organiza el código de forma más clara, legible y fácil de mantener que otras estructuras condicionales.&lt;/p&gt; &lt;p&gt;Como alternativa, existe el condicional &lt;a href=&quot;/js/condicional-if-else/&quot;&gt;if…else&lt;/a&gt; combinando varias cláusulas &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else if&lt;/code&gt; o incluso &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; anidados. Sin embargo, la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt; ofrece una sintaxis más limpia y estructurada: en vez de escribir múltiples condiciones, las agrupa en un solo bloque, facilitando la lectura de cada caso.&lt;/p&gt; &lt;h2 id=&quot;algoritmo&quot;&gt;Algoritmo&lt;/h2&gt; &lt;p&gt;Su funcionamiento es sencillo: primero se evalúa la expresión indicada; si su valor coincide con alguna de las etiquetas de caso (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;case&lt;/code&gt;), se ejecuta su bloque de código asociado. Si ninguna etiqueta coincide con el valor de la expresión, se ejecuta el bloque de código del caso por defecto (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default&lt;/code&gt;).&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-switch.svg&quot; alt=&quot;Diagrama de flujo de un condicional &apos;switch&apos;&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un condicional &apos;switch&apos;.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;Cada vez que se ejecuta el programa, la expresión se evalúa una sola vez. Si su valor coincide con el primer caso, se ejecuta su bloque asociado y se termina el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt;. Si no coincide con el primero continúa comprobando hasta llegar al último caso. Puede haber tantos casos como se necesiten, y si no se cumple ninguno, se ejecutará el código del bloque predeterminado (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default&lt;/code&gt;).&lt;/p&gt; &lt;h2 id=&quot;sintaxis&quot;&gt;Sintaxis&lt;/h2&gt; &lt;p&gt;La palabra reservada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt; marca el inicio de esta estructura condicional. Después, entre paréntesis (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;()&lt;/code&gt;) se indica la expresión que se quiere evaluar, y se comparará con los diferentes casos establecidos. Entre llaves (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{}&lt;/code&gt;) se incluyen todos los casos, y de forma opcional, el caso por defecto.&lt;/p&gt; &lt;p&gt;Su sintaxis es la siguiente:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;expresión&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si el valor es 1&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si el valor es 2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si el valor es 3&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nl&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si no es ninguno de&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// los anteriores&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;La expresión entre paréntesis puede ser una variable, una expresión matemática, el resultado de una función, una expresión lógica o incluso un &lt;a href=&quot;/js/tipos-datos/&quot;&gt;tipo de dato&lt;/a&gt;. En resumen, se trata de &lt;strong&gt;cualquier expresión evaluable que devuelve un valor&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;Cada caso se declara mediante la palabra reservada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;case&lt;/code&gt;, seguida del valor que se quiere comparar con la expresión. Dicho valor puede ser un número, una cadena de texto o un valor booleano. No obstante, no tendría sentido crear un &lt;strong&gt;switch&lt;/strong&gt; para decisiones tan simples que solo requieran dos posibles caminos.&lt;/p&gt; &lt;p&gt;Por último, la palabra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default&lt;/code&gt; es opcional y permite definir el bloque de código por defecto o predeterminado. Este código se ejecutará cuando ninguno de los casos anteriores coincida con el valor de la expresión. Haciendo una comparativa, actúa de forma similar a un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt; en una estructura &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if...else&lt;/code&gt;.&lt;/p&gt; &lt;h2 id=&quot;ejemplo-los-días-de-la-semana&quot;&gt;Ejemplo: los días de la semana&lt;/h2&gt; &lt;p&gt;Una de las formas más comunes de utilizar el condicional &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt; es cuando se desea ejecutar diferentes acciones según el valor de una variable concreta. En este ejemplo, si tenemos una variable que representa un número que va del 1 al 7, podemos asociar cada número con un día de la semana.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;dia&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;dia&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Lunes&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Martes&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Miércoles&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Jueves&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Viernes&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Sábado&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Domingo&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nl&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Número de día no válido&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Lo primero que hace el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt; es evaluar el valor de la variable &lt;var&gt;dia&lt;/var&gt;. El programa recorre los distintos casos (del 1 a 7) hasta encontrar una coincidencia exacta con el valor almacenado en la variable, y mostrará el mensaje correspondiente. Por tanto, si la variable &lt;var&gt;dia&lt;/var&gt; vale 3, el programa mostrará «Miércoles».&lt;/p&gt; &lt;p&gt;Cada bloque finaliza con la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt;, lo que indica que el programa debe salir del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt; una vez ejecutado el caso correcto. Si se omitiera el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt;, el flujo continuaría ejecutando los siguientes casos, dando resultados indeseados. A este comportamiento se le conoce como «&lt;em&gt;fall through&lt;/em&gt;».&lt;/p&gt; &lt;p&gt;Finalmente, si el valor de la variable no coincide con ninguno de los casos definidos, se ejecuta el bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;default&lt;/code&gt;, actuando como una especie de plan alternativo. Así se puede tomar decisiones cuando hay valores fuera del rango de 1 a 7.&lt;/p&gt; &lt;h2 id=&quot;ejemplo-las-notas-de-examen&quot;&gt;Ejemplo: las notas de examen&lt;/h2&gt; &lt;p&gt;Para profundizar más en el funcionamiento del condicional &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt;, veamos un ejemplo más complejo: analizar una nota de examen y mostrar su calificación textual (suspendido, aprobado, notable o sobresaliente). Para simplificarlo un poco, almacenamos la nota del estudiante en la variable &lt;var&gt;nota&lt;/var&gt;.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Suspendido&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Aprobado&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;nota&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Notable&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;nl&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Excelente&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;En este ejemplo, la instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;switch&lt;/code&gt; evalúa la expresión &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;. Aunque pueda parecer extraño, esta técnica es muy común cuando se quiere evaluar condiciones lógicas en lugar de valores exactos. De esta manera, cada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;case&lt;/code&gt; contiene una comparación comprobada de forma secuencial hasta que una de ellas devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;. En este punto se ejecuta el bloque correspondiente.&lt;/p&gt; &lt;p&gt;Como en el ejemplo anterior, si no se incluyera el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt;, el flujo de ejecución continuaría con los siguientes bloques, ejecutando todos los casos indicados. Esta “caída” o «&lt;em&gt;fall through&lt;/em&gt;» puede ser útil en situaciones concretas, aunque en la mayoría de los casos se evita para mantener un control más preciso.&lt;/p&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">El condicional switch es una instrucción que permite evaluar una expresión y ejecutar diferentes bloques de código según el valor obtenido. Resulta útil cuando se puede tener varios valores posibles, ya que organiza el código de forma más clara, legible y fácil de mantener que otras estructuras condicionales.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Condicional ‘if…else’ - Curso de JS</title><link href="https://recursivos.com/js/condicional-if-else/" rel="alternate" type="text/html" title="Condicional &apos;if...else&apos; - Curso de JS"/><published>2025-10-15T00:00:00+00:00</published><updated>2025-10-15T00:00:00+00:00</updated><id>https://recursivos.com/js/condicional-if-else</id><content type="html" xml:base="https://recursivos.com/js/condicional-if-else/">&lt;p&gt;En programación, muchas veces es necesario que el código tome decisiones. Por ejemplo, mostrar un mensaje si el usuario ha iniciado sesión, aplicar un descuento si el pedido supera cierta cantidad o permitir el acceso si se tiene permisos. En estos casos, el programa debe &lt;strong&gt;evaluar una condición&lt;/strong&gt; y ejecutar una operación u otra en función de si el resultado es verdadero o falso (un resultado &lt;strong&gt;booleano&lt;/strong&gt;).&lt;/p&gt; &lt;p&gt;En JavaScript existe la instrucción &lt;strong&gt;if…else&lt;/strong&gt; para tomar decisiones dinámicas según las circunstancias. Si la condición es verdadera, se ejecuta el bloque de código del &lt;strong&gt;if&lt;/strong&gt;. Si es falsa, se ejecuta un bloque alternativo usando &lt;strong&gt;else&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;JavaScript incluye varias formas de usar esta estructura condicional:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;/js/condicional-if-else/#if&quot;&gt;Instrucción &lt;strong&gt;if&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;/js/condicional-if-else/#if-else&quot;&gt;Instrucción &lt;strong&gt;if…else&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;/js/condicional-if-else/#if-else-if&quot;&gt;Instrucción &lt;strong&gt;if…else if…&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h2 id=&quot;instrucción-condicional&quot;&gt;Instrucción condicional&lt;/h2&gt; &lt;p&gt;Vamos a ver más de cerca cómo funcionan los condicionales. Una instrucción condicional permite &lt;strong&gt;controlar el flujo de ejecución&lt;/strong&gt; de un programa. Primero evalúa una expresión, como una comparación o el valor de una variable, y decide qué bloque de código ejecutar según si el resultado es &lt;strong&gt;verdadero o falso&lt;/strong&gt;.&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-condicional.svg&quot; alt=&quot;Diagrama de flujo de un condicional&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un condicional.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;En este diagrama de flujo se puede ver una bifurcación condicional. Si la condición evaluada devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero), se ejecutarán las sentencias agrupadas en el primer bloque del condicional. En caso contrario —si la condición devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso)—, se ejecutarán las del segundo bloque.&lt;/p&gt; &lt;h2 id=&quot;if&quot;&gt;La instrucción ‘if’&lt;/h2&gt; &lt;p&gt;La instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; puede usarse de una forma muy básica, ya que por si sola (sin el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt;) &lt;strong&gt;permite decidir si se ejecuta o no el código del bloque&lt;/strong&gt;.&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-if.svg&quot; alt=&quot;Diagrama de flujo de un condicional &apos;if&apos;&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un condicional &apos;if&apos;.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;Explicación: si la condición devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, se ejecutan las sentencias. En caso contrario, se salta la sentencias y el programa prosigue.&lt;/p&gt; &lt;p&gt;La sintaxis es la siguiente:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si la condición es true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Entre los paréntesis &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;()&lt;/code&gt; se indica la condición a evaluar. Puede ser una expresión lógica, aritmética, comparativa o booleana. Entre las llaves &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{}&lt;/code&gt; se incluyen las sentencias que se ejecutarán solo si la condición devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Eres mayor de 35&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;El mensaje solo se muestra si la variable &lt;var&gt;edad&lt;/var&gt; es mayor o igual que 35. Como «edad» vale 21, la condición es falsa y el mensaje no se muestra.&lt;/p&gt; &lt;h2 id=&quot;if-else&quot;&gt;La combinación ‘if else’&lt;/h2&gt; &lt;p&gt;La instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt; permite ejecutar sentencias cuando la condición indicada en el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;. En esencia, lo que hace es ampliar el control de flujo que ofrece &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt;, ya que permite &lt;strong&gt;definir dos caminos posibles&lt;/strong&gt;: uno cuando la condición es verdadera y otro cuando es falsa, creando así una &lt;strong&gt;bifurcación&lt;/strong&gt;.&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-if-else.svg&quot; alt=&quot;Diagrama de flujo de un condicional &apos;if...else&apos;&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un condicional &apos;if...else&apos;.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;Explicación: primero se evalúa la condición. Si el resultado es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, se ejecuta la sentencia 1 y se omite la sentencia 2. En caso contrario, resultado es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, por lo tanto se salta la sentencia 1 pero se ejecuta la sentencia 2.&lt;/p&gt; &lt;p&gt;Su sintaxis es la siguiente:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si la condición es true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si la condición es false&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Entre las segundas llaves &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{}&lt;/code&gt; —las que siguen al &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt;— se incluyen las sentencias que se ejecutan cuando la condición devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;Ampliando el ejemplo anterior:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Eres mayor de 35&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Eres menor de 35&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este caso, si la edad es mayor o igual que 35, se ejecuta el bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt;. De lo contrario, se ejecuta el bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt;.&lt;/p&gt; &lt;h2 id=&quot;if-else-if&quot;&gt;Varias condiciones: ‘if else if’&lt;/h2&gt; &lt;p&gt;La instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else if&lt;/code&gt; permite &lt;strong&gt;evaluar múltiples condiciones&lt;/strong&gt; dentro de una misma estructura. Esta instrucción se coloca después de la llave de cierre del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; inicial. Esta instrucción permite crear una ramificación múltiple sin tener que anidar varios &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt;; en realidad son bifurcaciones sucesivas.&lt;/p&gt; &lt;figure style=&quot;max-width: 100%&quot; class=&quot;align-center&quot;&gt; &lt;img src=&quot;/images/js/algoritmo-if-else-if.svg&quot; alt=&quot;Diagrama de flujo de un condicional &apos;if...else if...&apos;&quot; /&gt; &lt;figcaption&gt;Diagrama de flujo de un condicional &apos;if...else if...&apos;.&lt;/figcaption&gt; &lt;/figure&gt; &lt;p&gt;Explicación: primero se evalúa la condición 1; si es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; se ejecuta la sentencia 1, pero si no, se omite. Entonces se evalúa la condición 2; si es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; se ejecuta la sentencia 2, pero si no, se salta salta hasta el &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt;. En este punto, ninguna de las dos anteriores es &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, por lo que se ejecuta la sentencia 3.&lt;/p&gt; &lt;p&gt;Veamos su sintaxis:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si la condición 1 es true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;condición&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// si la condición 2 es true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Código que se ejecuta si&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// ninguna de las anteriores es true&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;JavaScript evalúa las opciones de arriba a abajo. Cada &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else if&lt;/code&gt; forma parte del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt; de la declaración anterior. Esto significa que el bloque que se ejecuta es aquel cuya condición devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;. En caso de que ninguna de las condiciones anteriores sea &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, se ejecuta el bloque final del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;Ampliando el ejemplo anterior:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Eres mayor de 35&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Tienes entre 30 y 34&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Tienes entre 25 y 29&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Eres menor de 25&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este caso, si la edad es mayor o igual que 35, se muestra el mensaje del bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt;. Si no lo es, se comprueba si es mayor o igual que 30 y, después, si es mayor o igual que 25. Si ninguna de las condiciones es verdadera, se ejecuta el bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt;.&lt;/p&gt; &lt;h2 id=&quot;condiciones-compuestas-con-operadores-lógicos&quot;&gt;Condiciones compuestas con operadores lógicos&lt;/h2&gt; &lt;p&gt;Hasta ahora hemos visto cómo evaluar una sola condición dentro de una estructura condicional. Sin embargo, en JavaScript es posible evaluar varias condiciones al mismo tiempo dentro de una misma instrucción. Esto se consigue combinándolas mediante los &lt;a href=&quot;/js/operadores-logicos/&quot;&gt;operadores lógicos&lt;/a&gt; &lt;strong&gt;AND&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&amp;amp;&lt;/code&gt;) y &lt;strong&gt;OR&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;||&lt;/code&gt;).&lt;/p&gt; &lt;h3 id=&quot;el-operador-and&quot;&gt;El operador &lt;em&gt;AND&lt;/em&gt;&lt;/h3&gt; &lt;p&gt;El operador &lt;strong&gt;AND&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&amp;amp;&lt;/code&gt;) se usa cuando todas las condiciones deben ser verdaderas. Si ambas condiciones son &lt;em&gt;truthy&lt;/em&gt;, la condición completa devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; y se ejecuta el bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt;. En caso contrario, el código se omite.&lt;/p&gt; &lt;p&gt;Sintaxis básica:&lt;/p&gt; &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;if (condición &amp;amp;&amp;amp; condición) { // El código se ejecuta si // ambas condiciones son verdaderas } &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;tieneCarnet&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;tieneCarnet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Puedes conducir&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, el mensaje se muestra solo si la persona tiene 18 años o más y además posee la licencia de conducir vehículos. Si una de las dos condiciones no se cumple, el mensaje no se muestra.&lt;/p&gt; &lt;h3 id=&quot;el-operador-or&quot;&gt;El operador &lt;em&gt;OR&lt;/em&gt;&lt;/h3&gt; &lt;p&gt;El operador &lt;strong&gt;OR&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;||&lt;/code&gt;) se usa cuando basta con que una de las condiciones sea verdadera. Si una de ellas es &lt;em&gt;truthy&lt;/em&gt;, devolverá &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; y se ejecutará el bloque del &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt;. Si ambas &lt;em&gt;falsy&lt;/em&gt;, el motor omitirá el bloque y saltará a la siguiente línea.&lt;/p&gt; &lt;p&gt;Sintaxis básica:&lt;/p&gt; &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;if (condición || condición) { // El código se ejecuta si // una condición es verdadera } &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;esAdmin&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;esEditor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;esAdmin&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;esEditor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Tienes acceso&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, el mensaje se muestra si el usuario es administrador o editor. Si ambas son falsas (valores &lt;em&gt;falsy&lt;/em&gt;), el mensaje no se muestra.&lt;/p&gt; &lt;h3 id=&quot;el-operador-not&quot;&gt;El operador &lt;em&gt;NOT&lt;/em&gt;&lt;/h3&gt; &lt;p&gt;El operador &lt;strong&gt;NOT&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!&lt;/code&gt;) permite negar el valor de una condición con el fin de devolver el valor opuesto. En otras palabras, si la condición es &lt;em&gt;truthy&lt;/em&gt;, el resultado será &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso); si es &lt;em&gt;falsy&lt;/em&gt;, el resultado será &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero).&lt;/p&gt; &lt;p&gt;Sintaxis básica:&lt;/p&gt; &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;if (!condición) { // El código se ejecuta // si la condición es falsa } &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;tieneCarnet&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;tieneCarnet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Eres mayor de edad, pero no tienes carnet&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, primero se evalúa si la persona es mayor de edad y luego si no tiene carnet. Solo si ambas condiciones se cumplen, se ejecuta el bloque.&lt;/p&gt; &lt;h3 id=&quot;agrupación-con-paréntesis&quot;&gt;Agrupación con paréntesis&lt;/h3&gt; &lt;p&gt;Los paréntesis son un gran aliado a para agrupar y organizar varias condiciones dentro de una misma instrucción &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt;. JavaScript evalúa primero los paréntesis internos y luego los externos, siguiendo la jerarquía que definamos.&lt;/p&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;edad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;esAdmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Acceso permitido&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, primero se evalúa si la edad está comprendida entre los 18 y 65 años. Si esta condición es verdadera o bien la persona es administrador, se ejecuta el bloque, mostrando el mensaje.&lt;/p&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">En programación, muchas veces es necesario que el código tome decisiones. Por ejemplo, mostrar un mensaje si el usuario ha iniciado sesión, aplicar un descuento si el pedido supera cierta cantidad o permitir el acceso si se tiene permisos. En estos casos, el programa debe evaluar una condición y ejecutar una operación u otra en función de si el resultado es verdadero o falso (un resultado booleano).</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Coerción de tipos de datos - Curso de JS</title><link href="https://recursivos.com/js/coercion-tipos/" rel="alternate" type="text/html" title="Coerción de tipos de datos - Curso de JS"/><published>2025-10-14T00:00:00+00:00</published><updated>2025-10-14T00:00:00+00:00</updated><id>https://recursivos.com/js/coercion-tipos</id><content type="html" xml:base="https://recursivos.com/js/coercion-tipos/">&lt;p&gt;La &lt;strong&gt;coerción de tipos&lt;/strong&gt; (o conversión implícita) ocurre cuando JavaScript &lt;strong&gt;convierte de forma automática un valor de un tipo de dato a otro tipo&lt;/strong&gt;. Este proceso se produce al realizar una operación, como un cálculo aritmético o una comparación, cuando el motor necesita un tipo de dato diferente para evaluarla.&lt;/p&gt; &lt;p&gt;¿Por qué se produce la coerción? Porque JavaScript es un lenguaje de tipado dinámico (débilmente tipado), lo que significa que los valores de las variables, constantes o funciones no tienen un tipo de dato fijo. De hecho, los &lt;a href=&quot;/js/tipos-datos/&quot;&gt;tipos de datos&lt;/a&gt; pueden cambiar varias veces durante la ejecución del programa.&lt;/p&gt; &lt;p&gt;Estas conversiones automáticas son esenciales para que el lenguaje pueda realizar operaciones de forma flexible. Sin embargo, comprender cómo y cuándo ocurren es fundamental, ya que la coerción puede generar resultados inesperados o errores de lógica. En contraste, la &lt;a href=&quot;/js/conversion-tipos/&quot;&gt;conversión explícita&lt;/a&gt; se realiza de forma intencional, usando funciones y métodos integrados en el propio lenguaje.&lt;/p&gt; &lt;p&gt;Un ejemplo de coerción. Si usamos el operador de adición (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;) cuyos operandos son un número (tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt;) y una cadena de texto (tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string&lt;/code&gt;), el motor convertirá el número a cadena y realizará una concatenación.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;hola&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;20hola&apos;&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;El resultado es una cadena de texto con el valor «20hola».&lt;/p&gt; &lt;p&gt;En cambio, si el operador es el de sustracción (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-&lt;/code&gt;) y la cadena de texto contiene un número válido (sin caracteres no numéricos), la cadena se convertirá a tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt; para efectuar la operación aritmética de forma correcta.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 15&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;Ahora sí ha realizado una operación aritmética.&lt;/p&gt; &lt;p&gt;Vamos a verlos con más detalle.&lt;/p&gt; &lt;h2 id=&quot;coerción-a-cadena-de-texto&quot;&gt;Coerción a cadena de texto&lt;/h2&gt; &lt;p&gt;La &lt;strong&gt;coerción a cadena de texto&lt;/strong&gt; ocurre cuando JavaScript necesita un valor de tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string&lt;/code&gt;. Esto sucede, por ejemplo, al usar el operador de adición (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;) cuando uno de los dos operandos es una cadena de texto y el otro no.&lt;/p&gt; &lt;p&gt;Las reglas de la coerción a cadena de texto son muy simples: todos los tipos de datos pueden ser convertidos a una representación textual usando su valor. Por ejemplo, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; se convierte en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;true&apos;&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;null&apos;&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;105000&apos;&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;10false&apos;&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;10null&apos;&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En estos ejemplos, JavaScript convierte a cadena de texto (tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string&lt;/code&gt;) los operandos «5000», «false» y «null» para realizar la concatenación.&lt;/p&gt; &lt;h2 id=&quot;coerción-a-número&quot;&gt;Coerción a número&lt;/h2&gt; &lt;p&gt;La &lt;strong&gt;coerción a número&lt;/strong&gt; se produce de forma automática cuando un valor de un tipo no numérico debe convertirse a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt;, porque así lo requiere la operación que se está realizando. Esto sucede con la mayoría de los operadores aritméticos (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;%&lt;/code&gt;) y de comparación relacional (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;=&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;=&lt;/code&gt;).&lt;/p&gt; &lt;p class=&quot;notice-warning&quot;&gt;Existe una excepción importante: el operador de adición (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;) &lt;strong&gt;no realiza la conversión implícita número&lt;/strong&gt; cuando uno de los operandos es una cadena de texto. En tal caso, JS realiza una concatenación.&lt;/p&gt; &lt;p&gt;Estas son las reglas de la coerción a número:&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: left&quot;&gt;Valor&lt;/th&gt; &lt;th style=&quot;text-align: left&quot;&gt;Conversión&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: left&quot;&gt;Cadenas de texto con números (‘123’)&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Números&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: left&quot;&gt;Cadenas de texto sin números (‘abc’)&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;em&gt;NaN&lt;/em&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: left&quot;&gt;Cadenas vacías o con espacios (‘’)&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: left&quot;&gt;El valor booleano &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: left&quot;&gt;El valor booleano &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: left&quot;&gt;La ausencia de valor (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;)&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: left&quot;&gt;Valor no asignado (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt;)&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;em&gt;NaN&lt;/em&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;Veamos algunos ejemplos para entenderlo mejor:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 2 (10 / 5)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 5 (10 - 5)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 9 (10 - 1)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0 (10 * 0)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;tp&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN (NaN / 50)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, las cadenas de texto ‘10’ y ‘5’ se convierten a números. Los valores booleanos &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; se convierten en 1 y 0, respectivamente. La cadena de texto ‘tp’ no contiene números, por tanto no puede realizar una operación y como resultado devuelve &lt;em&gt;NaN&lt;/em&gt; (&lt;em&gt;Not a Number&lt;/em&gt;).&lt;/p&gt; &lt;h3 id=&quot;conversión-de-null-a-número&quot;&gt;Conversión de ‘null’ a número&lt;/h3&gt; &lt;p&gt;El tipo de dato &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; (ausencia de valor) se convierte de forma automática a 0 cuando se usa como operando en un contexto que requiere un número.&lt;/p&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0 (10 * 0)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10 (10 - 0)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10 (10 + 0)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h3 id=&quot;conversión-de-undefined-a-número&quot;&gt;Conversión de ‘undefined’ a número&lt;/h3&gt; &lt;p&gt;El tipo de dato &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt; (valor no asignado) siempre se convierte a &lt;em&gt;NaN&lt;/em&gt; (&lt;em&gt;Not a Number&lt;/em&gt;) cuando se usa con operadores aritméticos. De hecho, cualquier operación aritmética que incluya &lt;em&gt;NaN&lt;/em&gt; será &lt;em&gt;NaN&lt;/em&gt;.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN (10 * NaN)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN (10 - NaN)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN (10 + NaN)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;coerción-a-booleano&quot;&gt;Coerción a booleano&lt;/h2&gt; &lt;p&gt;La &lt;strong&gt;coerción a booleano&lt;/strong&gt; se produce cuando un valor es evaluado en un contexto lógico, lo que requiere que el valor se interprete como verdadero o falso. Esto ocurre al aplicar el operador lógico &lt;em&gt;NOT&lt;/em&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!&lt;/code&gt;) de negación o al evaluar una estructura condicional, como puede ser un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if&lt;/code&gt; o un &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while&lt;/code&gt;.&lt;/p&gt; &lt;p class=&quot;notice-info&quot;&gt;Los valores se convierten de forma automática a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; dependiendo de su valor de verdad, conocido como la regla &lt;em&gt;truthy&lt;/em&gt; o &lt;em&gt;falsy&lt;/em&gt;.&lt;/p&gt; &lt;p&gt;Por tanto, la regla principal para la conversión automática de valores booleanos es la siguiente: los valores &lt;em&gt;falsy&lt;/em&gt; como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;&apos;&lt;/code&gt; (cadena vacía), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; se convierten a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso). Por el contrario, el resto son &lt;em&gt;truthy&lt;/em&gt;, en consecuencia se convierten a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdaderos).&lt;/p&gt; &lt;p&gt;Por ejemplo:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (0 es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (1 es truthy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (cadena vacía es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;ABC&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (string es truthy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (null es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NaN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (NaN es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{};&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (un objeto vacío es truthy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[];&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (un array vacío es truthy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;Como se puede ver, la negación de los valores &lt;em&gt;falsy&lt;/em&gt; devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, mientras que la negación de los valores &lt;em&gt;truthy&lt;/em&gt; devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;.&lt;/p&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">La coerción de tipos (o conversión implícita) ocurre cuando JavaScript convierte de forma automática un valor de un tipo de dato a otro tipo. Este proceso se produce al realizar una operación, como un cálculo aritmético o una comparación, cuando el motor necesita un tipo de dato diferente para evaluarla.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Conversión de tipos de datos - Curso de JS</title><link href="https://recursivos.com/js/conversion-tipos/" rel="alternate" type="text/html" title="Conversión de tipos de datos - Curso de JS"/><published>2025-10-12T00:00:00+00:00</published><updated>2025-10-12T00:00:00+00:00</updated><id>https://recursivos.com/js/conversion-tipos</id><content type="html" xml:base="https://recursivos.com/js/conversion-tipos/">&lt;p&gt;En programación, la &lt;strong&gt;conversión de tipos de datos&lt;/strong&gt; es el proceso mediante el cual se &lt;strong&gt;transforma el tipo de dato de un valor a otro&lt;/strong&gt;. Por ejemplo, un número puede convertirse en una cadena de texto, o una cadena en un valor booleano. Este tipo de conversiones permiten que los programas sean más flexibles al manejar información de distinta naturaleza, evitando errores o resultados inesperados.&lt;/p&gt; &lt;p&gt;En JavaScript, la conversión de tipos cobra importancia porque es un lenguaje débilmente tipado: las variables, constantes y funciones no tienen un tipo de dato fijo, por lo que pueden cambiar durante la ejecución. Pueden transformarse de forma automática (coerción o &lt;a href=&quot;/js/coercion-tipos/&quot;&gt;conversión implícita&lt;/a&gt;) o de forma intencional (conversión explícita), es decir, que el programador las realiza manualmente.&lt;/p&gt; &lt;p&gt;En este artículo nos centraremos en esta última: la &lt;strong&gt;conversión explícita de tipos&lt;/strong&gt;. A diferencia de la coerción, que ocurre de manera automática y a veces impredecible, la conversión explícita se realiza de manera consciente y controlada. JavaScript proporciona funciones y métodos, como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Number()&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;String()&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Boolean()&lt;/code&gt;, para transformar valores entre distintos tipos de forma más precisa.&lt;/p&gt; &lt;p&gt;Comprender y aplicar correctamente la conversión explícita es una práctica esencial para evitar errores lógicos y garantizar resultados coherentes, especialmente al trabajar con operaciones aritméticas o validaciones de datos.&lt;/p&gt; &lt;h2 id=&quot;conversión-explícita-a-cadena-de-texto&quot;&gt;Conversión explícita a cadena de texto&lt;/h2&gt; &lt;p&gt;Para &lt;strong&gt;convertir cualquier tipo de dato a una cadena de texto&lt;/strong&gt;, existen dos formas principales: usar el constructor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;String()&lt;/code&gt; o el método &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;toString()&lt;/code&gt;. Según el contexto, nos interesará más una forma o la otra.&lt;/p&gt; &lt;p&gt;El constructor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;String()&lt;/code&gt; es la opción más segura cuando el tipo de dato es incierto (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt;), ya que no produce error en estos casos. Basta con indicar como parámetro el dato que queremos convertir a cadena de texto.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nb&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;10&apos;&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;null&apos;&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;true&apos;&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;El método &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;toString()&lt;/code&gt;, en cambio, se invoca de forma directa sobre el valor o la variable. Por ejemplo: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;miNumero.toString()&lt;/code&gt;. Sin embargo, no puede usarse con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt;, porque no tienen métodos asociados.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;toString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;10&apos;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;toString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// Error&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Una ventaja de usar el método &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;toString()&lt;/code&gt; es que permite especificar como parámetro la base numérica en la que se representará el número. Por ejemplo, se puede convertir un número de base decimal (o base 10) en una cadena de texto que muestre su valor en base binaria (o base 2); de esta manera:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;toString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;1010&apos;&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;conversión-explícita-a-número&quot;&gt;Conversión explícita a número&lt;/h2&gt; &lt;p&gt;Para &lt;strong&gt;convertir valores a tipo numérico&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt;) de forma intencional se pueden usar varias opciones: el constructor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Number()&lt;/code&gt;, las funciones &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;parseInt()&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;parseFloat()&lt;/code&gt;, o bien el operador «unario más» (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+N&lt;/code&gt;).&lt;/p&gt; &lt;p&gt;El constructor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Number()&lt;/code&gt; se usa indicando como parámetro el valor que se desea convertir a tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt;. Puede recibir cadenas de texto que contengan números, valores booleanos o el valor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;. En cambio, si el valor es una cadena sin números o el valor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt;, devolverá &lt;em&gt;NaN&lt;/em&gt; (&lt;em&gt;Not a Number&lt;/em&gt;).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nb&quot;&gt;Number&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Number&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 1&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Number&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Number&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Number&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;ABC&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;En lugar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Number()&lt;/code&gt;, también puede usarse el operador «unario más» (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+N&lt;/code&gt;) como prefijo. Funciona de forma equivalente, pero es más breve:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;La función &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;parseInt()&lt;/code&gt; convierte cadenas de texto a &lt;strong&gt;números enteros&lt;/strong&gt;. Si el texto del parámetro indicado contiene un número con decimales, solo se conserva la parte entera. Además, acepta un segundo parámetro opcional para indicar la base numérica del primer parámetro (por defecto, base 10).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nb&quot;&gt;parseInt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;10.95&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;parseInt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10.9543&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;parseInt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;ABCD&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;parseInt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;parseInt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1010&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Por otro lado, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;parseFloat()&lt;/code&gt; permite convertir cadenas de texto a &lt;strong&gt;números de coma flotante&lt;/strong&gt; (con decimales). Admite un solo parámetro, que si no es una cadena de texto, primero se convierte a texto antes de ser analizado.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nb&quot;&gt;parseFloat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 3.14&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;parseFloat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;3.14&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 3.14&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;parseFloat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt; 3.14 &lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 3.14&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;parseFloat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;FF2&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// NaN&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;conversión-explícita-a-booleano&quot;&gt;Conversión explícita a booleano&lt;/h2&gt; &lt;p&gt;Para &lt;strong&gt;convertir cualquier tipo de dato a un valor booleano&lt;/strong&gt; (verdadero o falso) de forma voluntaria se utiliza el constructor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Boolean()&lt;/code&gt;. Este proceso convierte los valores en función de si son considerados &lt;em&gt;falsy&lt;/em&gt; o &lt;em&gt;truthy&lt;/em&gt;. De forma alternativa también puede usarse la doble negación (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!!&lt;/code&gt;).&lt;/p&gt; &lt;p&gt;Los valores &lt;em&gt;falsy&lt;/em&gt; —que se convierten en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;— son los siete siguientes: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;&apos;&lt;/code&gt; (cadena vacía), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;. Todos los demás valores se consideran &lt;em&gt;truthy&lt;/em&gt; y, por lo tanto, se convierten en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nb&quot;&gt;Boolean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Boolean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (0 es falsy)&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Boolean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (cadena vacía es falsy)&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Boolean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (null es falsy)&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Boolean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Hi&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;En lugar &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Boolean()&lt;/code&gt;, también puede usarse el doble operador de negación (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!!&lt;/code&gt;). El primer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!&lt;/code&gt; niega el valor de forma implícita, pero el segundo fuerza una nueva inversión, devolviendo el valor original ya convertido.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;!!&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;ABC&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (string es truthy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!!&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!!&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{};&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">En programación, la conversión de tipos de datos es el proceso mediante el cual se transforma el tipo de dato de un valor a otro. Por ejemplo, un número puede convertirse en una cadena de texto, o una cadena en un valor booleano. Este tipo de conversiones permiten que los programas sean más flexibles al manejar información de distinta naturaleza, evitando errores o resultados inesperados.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Operadores bit a bit - Curso de JS</title><link href="https://recursivos.com/js/operadores-bit-a-bit/" rel="alternate" type="text/html" title="Operadores bit a bit - Curso de JS"/><published>2025-10-09T00:00:00+00:00</published><updated>2025-10-09T00:00:00+00:00</updated><id>https://recursivos.com/js/operadores-bit-a-bit</id><content type="html" xml:base="https://recursivos.com/js/operadores-bit-a-bit/">&lt;p&gt;Los &lt;strong&gt;operadores bit a bit&lt;/strong&gt; (&lt;em&gt;bitwise&lt;/em&gt;) son símbolos que permiten trabajar de forma directa con la representación binaria de los números enteros. En lugar de operar sobre valores numéricos, evalúan y manipulan cada bit de sus operandos, de forma individual. Esto es esencial en operaciones de bajo nivel.&lt;/p&gt; &lt;p&gt;Estos operadores trabajan con operandos de 32 bits. Puesto que JavaScript guarda el tipo de dato &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt; como números de punto flotante de 64 bits, los convierte de forma automática. Antes de una operación &lt;strong&gt;bit a bit&lt;/strong&gt;, el valor se convierte a un entero con signo de 32 bits. Después de la operación, el resultado se convierte de nuevo al formato de punto flotante de 64 bits.&lt;/p&gt; &lt;p&gt;En JavaScript hay siete operadores de este tipo:&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Operador&lt;/th&gt; &lt;th style=&quot;text-align: left&quot;&gt;Nombre&lt;/th&gt; &lt;th style=&quot;text-align: left&quot;&gt;Descripción&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-bit-a-bit/#and-bit-bit&quot;&gt;&lt;em&gt;AND&lt;/em&gt; bit a bit&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Compara cada bit de los operandos y devuelve 1 si ambos son 1.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;|&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-bit-a-bit/#or-bit-bit&quot;&gt;&lt;em&gt;OR&lt;/em&gt; bit a bit&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Compara cada bit de los operandos y devuelve 1 si uno de los dos es 1.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;^&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-bit-a-bit/#xor-bit-bit&quot;&gt;&lt;em&gt;XOR&lt;/em&gt; bit a bit&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Devuelve 1 si los bits son distintos, y 0 si son iguales.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-bit-a-bit/#not-bit-bit&quot;&gt;&lt;em&gt;NOT&lt;/em&gt; bit a bit&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Operador unario: invierte cada bit del operando (complemento a uno).&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;&amp;lt;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-bit-a-bit/#izquierda-bit-bit&quot;&gt;Desplazamiento a la izquierda&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Desplaza los bits del operando izquierdo a la izquierda tantas posiciones como indique el operando derecho. Los espacios vacíos se rellenan con ceros. Equivale a multiplicar por potencias de 2.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-bit-a-bit/#derecha-bit-bit&quot;&gt;Desplazamiento a la derecha con signo&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Desplaza los bits del operando izquierdo a la derecha. Los bits de la izquierda se rellenan con el bit de signo (se conserva el signo del número).&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-bit-a-bit/#derecha-con-ceros&quot;&gt;Desplazamiento a la derecha con ceros&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Similar a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&lt;/code&gt;, pero siempre rellena con ceros por la izquierda, sin conservar el signo.&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;h2 id=&quot;and-bit-bit&quot;&gt;El operador AND bit a bit&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;AND bit a bit&lt;/strong&gt; se representa con un solo símbolo «&lt;em&gt;ampersand&lt;/em&gt;» (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&lt;/code&gt;). Este operador binario realiza la operación lógica &lt;em&gt;AND&lt;/em&gt; comparando, de forma individual, cada bit de sus dos operandos enteros.&lt;/p&gt; &lt;p&gt;Su funcionamiento es simple: si los dos bits comparados son 1, el bit resultante será 1. En cualquier otro caso, el bit resultante será 0.&lt;/p&gt; &lt;p&gt;Por ejemplo, comparemos &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9 &amp;amp; 5;&lt;/code&gt;. En sistema binario, el 9 es 1001 y el 5 es 0101, sin olvidar que JavaScript trabaja con 32 bits en vez de 4. Por cada par de bits obtenemos un bit resultante:&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Bit 1&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Bit 2&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Resultado (con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&lt;/code&gt;)&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, el único bit que resulta en 1 es el de la posición más a la derecha, porque ambos operandos tenían 1. El valor resultante es 0001, que en el sistema decimal equivale a 1. Por lo tanto: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9 &amp;amp; 5;&lt;/code&gt; es 1.&lt;/p&gt; &lt;h2 id=&quot;or-bit-bit&quot;&gt;El operador OR bit a bit&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;OR bit a bit&lt;/strong&gt; se representa con una sola barra vertical (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;|&lt;/code&gt;). Se trata de un operador binario que realiza la operación lógica &lt;em&gt;OR&lt;/em&gt; comparando los bits de forma individual de sus dos operandos enteros.&lt;/p&gt; &lt;p&gt;Su funcionamiento interno es el siguiente: si uno de los dos bits es 1, el bit resultante será 1. Si ninguno de los bits es 1, el bit resultante será 0.&lt;/p&gt; &lt;p&gt;Ahora comparemos &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9 | 5;&lt;/code&gt;. En sistema binario, tomando solo los últimos 4 bits en lugar de los 32 que utiliza JavaScript, el 9 es 1001 y el 5 es 0101. Tras comparar cada par de bits obtenemos un bit resultante:&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Bit 1&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Bit 2&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Resultado (con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;|&lt;/code&gt;)&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, el único bit que resulta en 0 es el tercero. Esto sucede porque ambos operandos tenían 0. El valor resultante es 1101, que traducido al sistema decimal es 13. Por tanto: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9 | 5;&lt;/code&gt; es 13.&lt;/p&gt; &lt;h2 id=&quot;xor-bit-bit&quot;&gt;El operador XOR bit a bit&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;XOR bit a bit&lt;/strong&gt; (o «OR exclusivo») se identifica con el símbolo del acento circunflejo (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;^&lt;/code&gt;). Es un operador binario que ejecuta la operación lógica &lt;em&gt;XOR&lt;/em&gt; al confrontar de manera individual cada bit de sus dos operandos enteros.&lt;/p&gt; &lt;p&gt;La lógica interna de esta operación se basa en la diferencia: el bit resultante será 1 solo si los dos bits comparados son distintos. Por tanto, si ambos bits son iguales (1 y 1, o 0 y 0), el bit resultante será 0.&lt;/p&gt; &lt;p&gt;Retomemos la comparación de los números 9 y 5: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9 ^ 5;&lt;/code&gt;. En la tabla siguiente se muestra la confrontación de cada par de bits y el valor obtenido:&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Bit 1&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Bit 2&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Resultado (con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;^&lt;/code&gt;)&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, el valor binario resultante es 1100, que traducido al sistema decimal es el 12. Este resultado se debe a que los dos primeros pares de operandos eran diferentes, resultando en 1, mientras que los dos últimos pares son iguales, resultando en 0. Por lo tanto: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9 ^ 5;&lt;/code&gt; equivale a 12.&lt;/p&gt; &lt;h2 id=&quot;not-bit-bit&quot;&gt;El operador NOT bit a bit&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;NOT bit a bit&lt;/strong&gt; (o «complemento a uno») se representa con la virguilla (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~&lt;/code&gt;). A diferencia de los operadores anteriores, este es un operador es &lt;strong&gt;unario&lt;/strong&gt;, ya que se aplica a un único operando entero. Su función es invertir el valor de cada bit del número: donde hay un 1, coloca un 0, y donde hay un 0, coloca un 1.&lt;/p&gt; &lt;p&gt;En otras palabras, el operador &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~&lt;/code&gt; niega todos los bits del número con el que trabaja. Además, es importante recordar que JavaScript utiliza una representación de 32 bits con signo para los números enteros en las operaciones bit a bit. De forma resumida: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~x&lt;/code&gt; equivale a la fórmula &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-(x + 1)&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;Vamos a ver un ejemplo con el número 5 (…00000101 en 32 bits). En la tabla siguiente solo mostramos la inversión en los últimos 4 bits:&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Bit original&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Inversión (con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~&lt;/code&gt;)&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p class=&quot;notice-info&quot;&gt;¡Ojo! Esto no significa que el resultado sea 10. El resultado de esta inversión (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~5;&lt;/code&gt;) es la representación binaria de -6 en 32 bits. Para simplificar el proceso, solo necesitamos recordar la fórmula que JavaScript aplica internamente. Por tanto, el resultado de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~7;&lt;/code&gt; será -8, y el de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;~8;&lt;/code&gt; será -9.&lt;/p&gt; &lt;h2 id=&quot;izquierda-bit-bit&quot;&gt;El operador &amp;lt;&amp;lt; bit a bit&lt;/h2&gt; &lt;p&gt;El operador de &lt;strong&gt;desplazamiento a la izquierda bit a bit&lt;/strong&gt; se representa con dos símbolos «menor que» (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;&amp;lt;&lt;/code&gt;). Este operador toma los bits de un número y los mueve hacia la izquierda tantas posiciones como se indique en el segundo operando. Por tanto, requiere dos operandos para funcionar.&lt;/p&gt; &lt;p&gt;Cada desplazamiento de una posición hacia la izquierda equivale a multiplicarlo por 2, cada desplazamiento de dos posiciones equivale a multiplicarlo por 4, y así sucesivamente. Por tanto, por cada desplazamiento se duplica el valor del número. Los espacios vacíos de la derecha se rellenan con ceros.&lt;/p&gt; &lt;p&gt;Veamos un ejemplo de desplazamiento del número 5 en varias posiciones hacia la izquierda. Para simplificar la visualización, la tabla solo muestra los bits relevantes, aunque JavaScript trabaja con 32 bits, rellenando el resto con ceros.&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Expresión (con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;&amp;lt;&lt;/code&gt;)&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Núm. binario&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Núm. decimal&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;lt;&amp;lt; 0;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0101&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;5&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;lt;&amp;lt; 1;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1010&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;10&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;lt;&amp;lt; 2;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;10100&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;20&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;lt;&amp;lt; 3;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;101000&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;40&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p class=&quot;notice-info&quot;&gt;Como podemos ver en esta tabla, cuantas más posiciones se desplazan los bits del número 5 en sistema binario, más grande es el valor del número decimal resultante, duplicándose cada vez respecto la anterior.&lt;/p&gt; &lt;h2 id=&quot;derecha-bit-bit&quot;&gt;El operador &amp;gt;&amp;gt; bit a bit&lt;/h2&gt; &lt;p&gt;El operador de &lt;strong&gt;desplazamiento a la derecha bit a bit&lt;/strong&gt; se representa mediante dos símbolos «mayor que» (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&lt;/code&gt;). Este operador desplaza los bits de un número hacia la derecha, tantas posiciones como se especifique en el segundo operando. Al igual que el operado anterior, requiere dos operandos.&lt;/p&gt; &lt;p&gt;Cada movimiento de una posición hacia la derecha equivale a dividir el número entre 2 y descartar cualquier resto decimal (redondeo a la baja). Así, por cada movimiento, el valor numérico entero se reduce casi a la mitad.&lt;/p&gt; &lt;p&gt;Dado que este desplazamiento es con signo, el bit que está más a la izquierda —el bit de signo, que es 0 para positivos y 1 para negativos— se preserva y se utiliza para rellenar los huecos que se abren a la izquierda. Esto garantiza que el signo del número no cambie durante la operación.&lt;/p&gt; &lt;p&gt;Vamos a crear un desplazamiento del número 5 en varias posiciones hacia la derecha. Nuevamente, para simplificar la visualización, la siguiente tabla solo muestra los bits relevantes, ya que JS trabaja con 32 bits.&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Expresión (con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&lt;/code&gt;)&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Núm. binario&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Núm. decimal&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;gt;&amp;gt; 0;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0101&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;5&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;gt;&amp;gt; 1;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0010&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;gt;&amp;gt; 2;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0001&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5 &amp;gt;&amp;gt; 3;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0000&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p class=&quot;notice-info&quot;&gt;Tal y como se puede ver en la tabla, a medida que los bits del número 5 se desplazan hacia la derecha, el valor decimal se reduce casi a la mitad en cada iteración: de 5 se pasa a 2, luego a 1 y, finalmente, a 0. Los bits desplazados fuera del rango por la derecha simplemente se descartan.&lt;/p&gt; &lt;h2 id=&quot;derecha-con-ceros&quot;&gt;El operador &amp;gt;&amp;gt;&amp;gt; bit a bit&lt;/h2&gt; &lt;p&gt;El operador de &lt;strong&gt;desplazamiento a la derecha sin signo&lt;/strong&gt; se representa con tres símbolos de «mayor que» (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt;). Este operador también desplaza los bits de un número hacia la derecha según el número de posiciones indicado en el segundo operando. Pero a diferencia de &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&lt;/code&gt;, ignora el bit de signo del número, rellenando los espacios vacíos que se abren a la izquierda con ceros.&lt;/p&gt; &lt;p&gt;Por tanto, este operador es idéntico a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&lt;/code&gt; para los números positivos. Sin embargo, es muy distinto para los números negativos: el relleno con ceros en la izquierda convierte el número de negativo a positivo.&lt;/p&gt; &lt;p&gt;Vamos a ver un ejemplo con un número negativo: -5. En el formato de 32 bits, el -5 comienza con 1, el bit que indica el signo negativo, mientras que el 5 desplazado comienza con 0, es decir, de signo positivo.&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Expresión (con &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt;)&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Núm. binario&lt;/th&gt; &lt;th style=&quot;text-align: center&quot;&gt;Núm. decimal&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-5 &amp;gt;&amp;gt;&amp;gt; 0;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;111…1011&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;4294967291&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-5 &amp;gt;&amp;gt;&amp;gt; 1;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;011…1101&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;2147483645&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-5 &amp;gt;&amp;gt;&amp;gt; 2;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;001…1110&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;1073741822&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-5 &amp;gt;&amp;gt;&amp;gt; 3;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;000…1111&lt;/td&gt; &lt;td style=&quot;text-align: center&quot;&gt;536870911&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p class=&quot;notice-info&quot;&gt;Como se observa en la tabla, el operador &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt; tiene un efecto drástico sobre los números negativos. Incluso cuando el desplazamiento es cero (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-5 &amp;gt;&amp;gt;&amp;gt; 0;&lt;/code&gt;), el valor original negativo se convierte en un número positivo extremadamente grande (4294967291). A partir de ahí, cada desplazamiento posterior reduce ese gran valor aproximadamente a la mitad.&lt;/p&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">Los operadores bit a bit (bitwise) son símbolos que permiten trabajar de forma directa con la representación binaria de los números enteros. En lugar de operar sobre valores numéricos, evalúan y manipulan cada bit de sus operandos, de forma individual. Esto es esencial en operaciones de bajo nivel.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Operadores lógicos - Curso de JS</title><link href="https://recursivos.com/js/operadores-logicos/" rel="alternate" type="text/html" title="Operadores lógicos - Curso de JS"/><published>2025-10-08T00:00:00+00:00</published><updated>2025-10-08T00:00:00+00:00</updated><id>https://recursivos.com/js/operadores-logicos</id><content type="html" xml:base="https://recursivos.com/js/operadores-logicos/">&lt;p&gt;Los &lt;strong&gt;operadores lógicos&lt;/strong&gt; se utilizan para combinar o invertir expresiones booleanas, que siempre se evalúan como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;. En JavaScript hay tres operadores lógicos principales: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&amp;amp;&lt;/code&gt; (&lt;em&gt;AND&lt;/em&gt;), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;||&lt;/code&gt; (&lt;em&gt;OR&lt;/em&gt;) y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!&lt;/code&gt; (&lt;em&gt;NOT&lt;/em&gt;). Son esenciales para construir condiciones complejas y controlar el flujo del programa.&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Operador&lt;/th&gt; &lt;th style=&quot;text-align: left&quot;&gt;Nombre&lt;/th&gt; &lt;th style=&quot;text-align: left&quot;&gt;Descripción&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&amp;amp;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-logicos/#and&quot;&gt;AND&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Devuelve verdadero si ambos operandos son &lt;em&gt;truthy&lt;/em&gt;.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;||&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-logicos/#or&quot;&gt;OR&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Devuelve verdadero si uno de los dos operandos es &lt;em&gt;truthy&lt;/em&gt;.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-logicos/#not&quot;&gt;NOT&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Niega el valor (devuelve el valor opuesto).&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;Los operadores lógicos no se limitan a trabajar con valores booleanos (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;). Si los operandos son de otro tipo (como &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt; o &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string&lt;/code&gt;), el lenguaje evalúa su “valor lógico”, es decir, si son «&lt;em&gt;falsy&lt;/em&gt;» o «&lt;em&gt;truthy&lt;/em&gt;».&lt;/p&gt; &lt;p&gt;Un valor &lt;em&gt;falsy&lt;/em&gt; es aquel que se considera falso al convertirlo a booleano. Se trata de los siguientes valores: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;&apos;&lt;/code&gt; (cadena vacía), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;null&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;undefined&lt;/code&gt; y &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;. En consecuencia, todos los demás se consideran &lt;em&gt;truthy&lt;/em&gt;, es decir, los que se consideran verdaderos después de convertidos a booleanos. Esto sería: cualquier número distinto de cero, cualquier cadena no vacía, etc.&lt;/p&gt; &lt;h2 id=&quot;and&quot;&gt;El operador &lt;em&gt;AND&lt;/em&gt;&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;AND&lt;/strong&gt; se representa con el doble signo «&lt;em&gt;ampersand&lt;/em&gt;» (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&amp;amp;&lt;/code&gt;) y evalúa las expresiones secuencialmente, siguiendo el orden de izquierda a derecha. Desde una perspectiva lógica (booleana), el resultado de la operación &lt;strong&gt;es verdadero solo si todos los operandos son considerados verdaderos&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;Pero el mecanismo interno de JavaScript es más complejo y utiliza la evaluación en «cortocircuito» (&lt;em&gt;short-circuiting&lt;/em&gt;). En realidad, el operador &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&amp;amp;&lt;/code&gt; &lt;strong&gt;busca el primer valor &lt;em&gt;falsy&lt;/em&gt;&lt;/strong&gt;. Si el primer operando que se evalúa es considerado &lt;em&gt;falsy&lt;/em&gt;, la evaluación se detiene y el operador devuelve inmediatamente ese valor &lt;em&gt;falsy&lt;/em&gt;.&lt;/p&gt; &lt;p&gt;En cambio, si el operando actual es &lt;em&gt;truthy&lt;/em&gt;, la evaluación continúa con el siguiente operando, y así sucesivamente hasta el final. Si todos los operandos resultan ser &lt;em&gt;truthy&lt;/em&gt;, el operador devuelve el valor del último operando.&lt;/p&gt; &lt;p&gt;Tomemos como ejemplo la expresión &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x &amp;amp;&amp;amp; y&lt;/code&gt;. Si la variable &lt;var&gt;x&lt;/var&gt; tiene un valor &lt;em&gt;falsy&lt;/em&gt;, devolverá el valor de &lt;var&gt;x&lt;/var&gt;. Si es &lt;em&gt;truthy&lt;/em&gt;, evaluará el valor del siguiente operando (&lt;var&gt;y&lt;/var&gt;). Al tratarse del último operando, el operador devolverá el valor de &lt;var&gt;y&lt;/var&gt;. Esta regla se aplica a todos los tipos de datos (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;string&lt;/code&gt;, etc).&lt;/p&gt; &lt;p class=&quot;notice-info&quot;&gt;Como regla general, hay que tener claro que el operador &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;amp;&amp;amp;&lt;/code&gt; siempre devuelve el valor del último operando evaluado.&lt;/p&gt; &lt;p&gt;Veamos algunos ejemplos de operandos de tipo booleano:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (ambos son truthy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (el segundo es falsy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (el primero es falsy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (ambos son falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Algunos ejemplos con operandos numéricos:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0 (el primero es falsy)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 4 (ambos son truthy)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0 (el segundo es falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos con cadenas de texto:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// vacío (el primero es falsy)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// B (ambos son truthy)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// vacío (el segundo es falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos variados:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Hola&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0 (el primero es falsy)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Hola&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;123&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 123 (ambos son truthy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// null (el primero es falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;or&quot;&gt;El operador &lt;em&gt;OR&lt;/em&gt;&lt;/h2&gt; &lt;p&gt;El operador &lt;em&gt;OR&lt;/em&gt; se representa con el doble símbolo de barra vertical (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;||&lt;/code&gt;). Al igual que &lt;em&gt;AND&lt;/em&gt;, también evalúa las expresiones de izquierda a derecha. Pero hay una diferencia clara: en este caso, el resultado de la operación &lt;strong&gt;es verdadero si al menos uno de los operandos es considerado verdadero&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;Su funcionamiento interno es el siguiente: el operador &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;||&lt;/code&gt; &lt;strong&gt;busca el primer valor &lt;em&gt;truthy&lt;/em&gt;&lt;/strong&gt;. Si el primer operando que se evalúa es considerado verdadero (&lt;em&gt;truthy&lt;/em&gt;), la evaluación se detiene y el operador devuelve ese valor &lt;em&gt;truthy&lt;/em&gt;.&lt;/p&gt; &lt;p&gt;En cambio, si el operando actual es &lt;em&gt;falsy&lt;/em&gt;, la evaluación continúa hasta el siguiente operando, y así sucesivamente hasta el final. Si todos los operandos resultan ser &lt;em&gt;falsy&lt;/em&gt;, el operador devolverá el valor del último operando.&lt;/p&gt; &lt;p&gt;Imaginemos el siguiente ejemplo: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x || y&lt;/code&gt;. Si la variable &lt;var&gt;x&lt;/var&gt; tiene un valor &lt;em&gt;truthy&lt;/em&gt;, el operador devolverá su valor. Si es &lt;em&gt;falsy&lt;/em&gt;, evaluará el valor del siguiente operando (&lt;var&gt;y&lt;/var&gt;). En este caso, se trata del último operando y devolverá el valor de &lt;var&gt;y&lt;/var&gt;.&lt;/p&gt; &lt;p class=&quot;notice-info&quot;&gt;Resumiendo lo importante, no hay que olvidar que el operador &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;||&lt;/code&gt; siempre devuelve el primer valor &lt;em&gt;truthy&lt;/em&gt; que encuentra; y si todos los operandos son &lt;em&gt;falsy&lt;/em&gt;, entonces devuelve el último operando evaluado.&lt;/p&gt; &lt;p&gt;Ejemplos usando operandos booleanos:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (el primero es truthy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (el primero es truthy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (el segundo es truthy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (ambos son falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos usando operandos numéricos:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10 (el segundo es truthy)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 10 (el primero es truthy)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 25 (el primero es truthy)&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0 (ambos son falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos con cadenas de texto:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;A&apos; (el segundo es truthy)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;A&apos; (el primero es truthy)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;C&apos; (el primero es truthy)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &apos;&apos; (ambos son falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos variados:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Hola&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &quot;Hola&quot; (el segundo es truthy)&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;Hola&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;123&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// &quot;Hola&quot; (el primero es truthy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (el segundo es truthy)&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;||&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 0 (ambos son falsy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;not&quot;&gt;El operador &lt;em&gt;NOT&lt;/em&gt;&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;NOT&lt;/strong&gt; está representado con el signo de exclamación (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!&lt;/code&gt;) y se aplica a un único operando. Por tanto, es un operador unario. Su función es &lt;strong&gt;invertir el valor lógico&lt;/strong&gt; (booleano) del operando. Si el operando es &lt;em&gt;truthy&lt;/em&gt;, el resultado será &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso), y si es &lt;em&gt;falsy&lt;/em&gt;, el resultado será &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero).&lt;/p&gt; &lt;p&gt;Desde una perspectiva lógica, podemos decir que este operador convierte cualquier valor a su equivalente booleano opuesto. Para ello, primero realiza una conversión implícita (coerción) al tipo de dato &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;boolean&lt;/code&gt; (booleano). Por esta razón, el operador &lt;em&gt;NOT&lt;/em&gt; siempre devuelve un valor estrictamente booleano.&lt;/p&gt; &lt;p class=&quot;notice-info&quot;&gt;Como regla general, hay que tener en cuenta que el operador &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!&lt;/code&gt; niega el valor lógico del operando después de convertirlo a booleano.&lt;/p&gt; &lt;p&gt;Veamos algunos ejemplos con valores booleanos:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos usando operandos numéricos:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (0 es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;123&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (123 es truthy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos con cadenas de texto:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (cadena vacía es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;Hola&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (cadena de texto es truthy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p&gt;Ejemplos variados:&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (null es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;undefined&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (undefined es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NaN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true (NaN es falsy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{};&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (objeto es truthy)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[];&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false (array vacío es truthy)&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">Los operadores lógicos se utilizan para combinar o invertir expresiones booleanas, que siempre se evalúan como true o false. En JavaScript hay tres operadores lógicos principales: &amp;amp;&amp;amp; (AND), || (OR) y ! (NOT). Son esenciales para construir condiciones complejas y controlar el flujo del programa.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry><entry><title type="html">Operadores de comparación - Curso de JS</title><link href="https://recursivos.com/js/operadores-comparacion/" rel="alternate" type="text/html" title="Operadores de comparación - Curso de JS"/><published>2025-10-07T00:00:00+00:00</published><updated>2025-10-07T00:00:00+00:00</updated><id>https://recursivos.com/js/operadores-comparacion</id><content type="html" xml:base="https://recursivos.com/js/operadores-comparacion/">&lt;p&gt;Los &lt;strong&gt;operadores de comparación&lt;/strong&gt; son símbolos que permiten comparar dos valores y obtener un resultado booleano: verdadero o falso. Las comparaciones posibles son bastante habituales, pues permiten determinar si dos valores son iguales, diferentes, menores o mayores. Por tanto, permiten evaluar expresiones.&lt;/p&gt; &lt;p&gt;Es evidente, por lógica, que los operadores de comparación son de tipo binario, ya que requieren dos operandos para poder realizar una comparación. Dichos operandos pueden ser datos de cualquier tipo, como podría ser dos números, dos cadenas de texto, valores lógicos, objetos o &lt;em&gt;arrays&lt;/em&gt;.&lt;/p&gt; &lt;p&gt;En JavaScript hay ocho operadores de este tipo:&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style=&quot;text-align: center&quot;&gt;Operador&lt;/th&gt; &lt;th style=&quot;text-align: left&quot;&gt;Nombre&lt;/th&gt; &lt;th style=&quot;text-align: left&quot;&gt;Descripción&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;==&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#igualdad&quot;&gt;Igualdad&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si dos valores son iguales, realizando conversión de tipo si es necesario.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;===&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#igualdad-estricta&quot;&gt;Igualdad estricta&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si dos valores son iguales y del mismo tipo.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!=&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#desigualdad&quot;&gt;Desigualdad&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si dos valores son diferentes, realizando conversión de tipo si es necesario.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!==&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#desigualdad-estricta&quot;&gt;Desigualdad estricta&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si dos valores son diferentes o de distinto tipo.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#mayor-que&quot;&gt;Mayor que&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si el operando izquierdo es mayor que el derecho.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#menor-que&quot;&gt;Menor que&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si el operando izquierdo es menor que el derecho.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;=&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#mayor-igual-que&quot;&gt;Mayor o igual que&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si el operando izquierdo es mayor o igual que el derecho.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;=&lt;/code&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;&lt;a href=&quot;/js/operadores-comparacion/#menor-igual-que&quot;&gt;Menor o igual que&lt;/a&gt;&lt;/td&gt; &lt;td style=&quot;text-align: left&quot;&gt;Comprueba si el operando izquierdo es menor o igual que el derecho.&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;En la mayoría de los operadores de comparación, JavaScript realiza &lt;strong&gt;coerción de tipo&lt;/strong&gt; cuando los operandos son de &lt;a href=&quot;/js/tipos-datos/&quot;&gt;tipos de datos&lt;/a&gt; diferentes. La excepción a esta regla son los operadores de igualdad estricta (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;===&lt;/code&gt;) y desigualdad estricta (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!==&lt;/code&gt;), que comparan los valores sin ninguna conversión de tipo.&lt;/p&gt; &lt;p&gt;Durante el proceso de coerción, si una cadena de texto contiene un valor numérico, se convierte al tipo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;number&lt;/code&gt;. Si contiene caracteres no numéricos, se convierte a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; (&lt;em&gt;Not a Number&lt;/em&gt;). Si la cadena está vacía, se convierte en &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;.&lt;/p&gt; &lt;h2 id=&quot;igualdad&quot;&gt;Igualdad&lt;/h2&gt; &lt;p&gt;El operador de &lt;strong&gt;igualdad&lt;/strong&gt; está representado por dos caracteres del símbolo igual (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;==&lt;/code&gt;) y comprueba si el valor de dos operandos es idéntico o no. Devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero) si sin iguales; en caso contrario, devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso). Si son de diferente tipo se realiza la conversión de tipo.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;p class=&quot;notice-info&quot;&gt;En este ejemplo, la última comparación devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero) porque JavaScript convierte la cadena de texto &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;4&apos;&lt;/code&gt; al tipo numérico &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4&lt;/code&gt;. Después de la coerción, evalúa la igualdad.&lt;/p&gt; &lt;h2 id=&quot;igualdad-estricta&quot;&gt;Igualdad estricta&lt;/h2&gt; &lt;p&gt;El operador de &lt;strong&gt;igualdad estricta&lt;/strong&gt;, compuesto por tres caracteres del símbolo igual (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;===&lt;/code&gt;), comprueba si el valor de dos operandos es idéntico, pero además comprueba que sean del mismo tipo. JavaScript no realizará la conversión de tipo. Por tanto, si son de diferente tipo, devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;desigualdad&quot;&gt;Desigualdad&lt;/h2&gt; &lt;p&gt;La &lt;strong&gt;desigualdad&lt;/strong&gt; viene representada por el signo de exclamación y el igual (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!=&lt;/code&gt;). Este operador comprueba si los valores de dos operandos no son iguales. Si no son iguales, devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero); en caso contrario, devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso). En caso de ser necesario, realiza la coerción del tipo de dato.&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;desigualdad-estricta&quot;&gt;Desigualdad estricta&lt;/h2&gt; &lt;p&gt;El operador de &lt;strong&gt;desigualdad estricta&lt;/strong&gt; está compuesto por el signo de exclamación y dos caracteres del símbolo igual (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;!==&lt;/code&gt;). Este operador devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero) si dos operandos no son idénticos o si no son del mismo tipo. En cambio, si son iguales y del mismo tipo devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!==&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;mayor-que&quot;&gt;Mayor que&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;mayor que&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&lt;/code&gt;) comprueba si el valor del operando de la izquierda es mayor que el valor del operando de la derecha. Si es afirmativa, dicha comparación devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero); en caso contrario, devuelve &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;menor-que&quot;&gt;Menor que&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;menor que&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&lt;/code&gt;) comprueba si el valor del operando de la izquierda es menor que el valor del operando de la derecha. En caso de ser cierto, el resultado será &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero); en caso contrario, será &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;mayor-igual-que&quot;&gt;Mayor o igual que&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;mayor o igual que&lt;/strong&gt; está formado por dos caracteres: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;=&lt;/code&gt;. Comprueba si el valor del operando de la izquierda es mayor o igual que el operando de la derecha. Por tanto, si es mayor o contiene el mismo valor, devolverá &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero); en caso contrario, devolverá &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt; &lt;h2 id=&quot;menor-igual-que&quot;&gt;Menor o igual que&lt;/h2&gt; &lt;p&gt;El operador &lt;strong&gt;menor o igual que&lt;/strong&gt; usa estos dos símbolos: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;=&lt;/code&gt;. Lo que hace es revisar que el valor del operando izquierdo sea menor o igual que el operando de la derecha. Si es menor o contiene el mismo valor, devolverá &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt; (verdadero); pero en caso contrario, devolverá &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; (falso).&lt;/p&gt; &lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt; &lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>Recursivos</name></author><category term="JS"/><category term="JS-art"/><summary type="html">Los operadores de comparación son símbolos que permiten comparar dos valores y obtener un resultado booleano: verdadero o falso. Las comparaciones posibles son bastante habituales, pues permiten determinar si dos valores son iguales, diferentes, menores o mayores. Por tanto, permiten evaluar expresiones.</summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://recursivos.com/images/recursos/js.png"/></entry></feed>