Comparación de JavaScript y operadores lógicos


Tabla de contenido

    Mostrar tabla de contenidos


Los operadores lógicos y de comparación se utilizan para probar true o falso.


Operadores de comparación

Los operadores de comparación se utilizan en declaraciones lógicas para determinar la igualdad o diferencia entre variables o valores.

Dado que x=5, la siguiente tabla explica los operadores de comparación:

==

Descripción: igual a

Comparando:

x == 8

Devoluciones :

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 8):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == 8);
</script>

</body>
</html>

Comparando:

x == 5

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == 5);
</script>

</body>
</html>

Comparando:

x == "5"

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == "5");
</script>

</body>
</html>

===

Descripción: valor igual y tipo igual

Comparando:

x === 5	

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The === Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x === 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x === 5);
</script>

</body>
</html>

Comparando:

x === "5"

Devoluciones :

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The === Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x === "5").</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x === "5");
</script>

</body>
</html>

!=

Descripción: no igual

Comparando:

x != 8

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The != Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x != 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x != 8);
</script>

</body>
</html>

!==

Descripción: valor diferente o tipo diferente

Comparando:

x !== 5

Devoluciones :

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The !== Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x !== 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x !== 5);
</script>

</body>
</html>

Comparando:

x !== "5"

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The !== Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x !== "5"):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x !== "5");
</script>

</body>
</html>

Comparando:

x !== 8

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The !== Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x !== 8):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x !== 8);
</script>

</body>
</html>

>

Descripción: mayor que

Comparando:

x > 8

Devoluciones :

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &gt; Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &gt; 8).</p>
 
<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x > 8);
</script>

</body>
</html>

<

Descripción: menos de

Comparando:

x < 8

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &lt; Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &lt; 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x < 8);
</script>

</body>
</html>

>=

Descripción: mayor o igual a

Comparando:

x >= 8

Devoluciones :

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &gt;= Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &gt;= 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x >= 8);
</script>

</body>
</html>

<=

Descripción: menor o igual a

Comparando:

x <= 8

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &lt;= Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &lt;= 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x <= 8);
</script>

</body>
</html>


Como puede ser usado

Los operadores de comparación se pueden utilizar en declaraciones condicionales para comparar valores. y actuar en función del resultado:

if (age < 18) text = "Too young to buy alcohol";

Aprenderá más sobre el uso de declaraciones condicionales en el próximo capítulo de este tutorial.


Operadores logicos

Los operadores lógicos se utilizan para determinar la lógica entre variables o valores.

Dado que x=6 y y=3, la siguiente tabla explica los operadores lógicos:

&&

Descripción: y

Comparando:

 (x < 10 && y > 1)

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The && Operator (Logical AND)</h2>
<p>The && operator returns true if both expressions are true, otherwise it returns false.</p>

<p id="demo"></p>

<script>
let x = 6;
let y = 3;

document.getElementById("demo").innerHTML = 
(x < 10 && y > 1) + "<br>" + 
(x < 10 && y < 1);
</script>

</body>
</html>

||

Descripción: o

Comparando:

(x == 5 || y == 5)

Devoluciones :

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The || Operator (Logical OR)</h2>
<p>The || returns true if one or both expressions are true, otherwise it returns false.</p>

<p id="demo"></p>

<script>
let x = 6;
let y = 3;

document.getElementById("demo").innerHTML = 
(x == 5 || y == 5) + "<br>" + 
(x == 6 || y == 0) + "<br>" + 
(x == 0 || y == 3) + "<br>" + 
(x == 6 || y == 3);
</script>

</body>
</html>

!

Descripción: no

Comparando:

!(x == y)

Devoluciones :

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p>The NOT operator (!) returns true for false statements and false for true statements.</p>

<p id="demo"></p>

<script>
let x = 6;
let y = 3;

document.getElementById("demo").innerHTML = 
!(x === y) + "<br>" + 
!(x > y);
</script>

</body>
</html>

Operador condicional (ternario)

JavaScript también contiene un operador condicional que asigna un valor a una variable en función de alguna condición.

Sintaxis

variablename = (condition) ? value1:value2 

Ejemplo

let voteable = (age < 18) ? "Too young":"Old enough";

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The () ? : Ternary Operator</h2>

<p>Input your age and click the button:</p>

<input id="age" value="18" />

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  let age = document.getElementById("age").value;
  let voteable = (age < 18) ? "Too young":"Old enough";
  document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>

</body>
</html>

Si la variable edad es un valor inferior a 18 años, el valor de la variable votable será "Demasiado joven"; de lo contrario, el valor de votable será "Suficientemente mayor".


Comparando diferentes tipos

La comparación de datos de diferentes tipos puede dar resultados inesperados.

Al comparar una cadena con un número, JavaScript convertirá la cadena en un número al hacer la comparación. Una cadena vacía se convierte en 0. Una cadena no numérica la cadena se convierte a NaN que siempre es false.

2 < 12

Valor:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 2 < 12;
</script>

</body>
</html>

2 < "12"

Valor:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 2 < "12";
</script>

</body>
</html>

2 < "John"

Valor:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 2 < "John";
</script>

</body>
</html>

2 > "John"

Valor:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 2 > "John";
</script>

</body>
</html>

2 == "John"

Valor:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 2 == "John";
</script>

</body>
</html>

"2" < "12"

Valor:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "2" < "12";
</script>

</body>
</html>

"2" > "12"

Valor:

true

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "2" > "12";
</script>

</body>
</html>

"2" == "12"

Valor:

false

Pruébalo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparison</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "2" == "12";
</script>

</body>
</html>

Al comparar dos cadenas, "2" será mayor que "12", porque (alfabéticamente) 1 es menor que 2.

Para garantizar un resultado adecuado, las variables deben convertirse al tipo adecuado antes de la comparación:

age = Number(age);
if (isNaN(age)) {
  voteable = "Input is not a number";
} else {
    voteable = (age < 18) ? "Too young" : "Old enough";
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comparisons</h2>

<p>Input your age and click the button:</p>

<input id="age" value="18" />

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  let voteable;
  let age = Number(document.getElementById("age").value);
  if (isNaN(age)) {
    voteable = "Input is not a number";
  } else {
    voteable = (age < 18) ? "Too young" : "Old enough";
  }
  document.getElementById("demo").innerHTML = voteable + " to vote";
}
</script>

</body>
</html>

El operador coalescente nulo (??)

El operador ?? devuelve el primer argumento si no es nulo (nulo o indefinido).

De lo contrario, devuelve el segundo argumento.

Ejemplo

let name = null;
let text = "missing";
let result = name ?? text;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The ?? Operator</h2>
<p>The ?? operator returns the first argument if it is not nullish (null or undefined). Otherwise it returns the second.</p>

<p id="demo"></p>

<script>
let name = null;
let text = "missing";
let result = name ?? text;
document.getElementById("demo").innerHTML = "The name is " + result; 
</script>

</body>
</html>


El operador nulo es compatible con todos los navegadores desde marzo de 2020:

Chrome 80 Edge 80 Firefox 72 Safari 13.1 Opera 67
Feb 2020 Feb 2020 Jan 2020 Mar 2020 Mar 2020

El operador de encadenamiento opcional (?.)

El operador ?. devuelve undefinido si un objeto es undefinido o null (en lugar de generar un error).

Ejemplo

// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
// Ask for car name:
document.getElementById("demo").innerHTML = car?.name;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The ?. Operator</h2>
<p>The ?. operator returns undefined if an object is undefined or null (instead of throwing an error).</p>

<p>Car name is:</p>
<p id="demo"></p>

<script>
const car = {type:"Fiat", model:"500", color:"white"};
let name = car?.name;
document.getElementById("demo").innerHTML = name;
</script>

</body>
</html>

El operador de encadenamiento opcional es compatible con todos los navegadores desde marzo de 2020:

Chrome 80 Edge 80 Firefox 72 Safari 13.1 Opera 67
Feb 2020 Feb 2020 Jan 2020 Mar 2020 Mar 2020