Como comparar um boolean em js

Comparison operators compare two values and give back a boolean value: either true or false. Comparison operators are used in decision making and loops.

Operator Description Example
== Equal to: true if the operands are equal 5==5; //true
!= Not equal to: true if the operands are not equal 5!=5; //false
=== Strict equal to: true if the operands are equal and of the same type 5==='5'; //false
!== Strict not equal to: true if the operands are equal but of different type or not equal at all 5!=='5'; //true
> Greater than: true if the left operand is greater than the right operand 3>2; //true
>= Greater than or equal to: true if the left operand is greater than or equal to the right operand 3>=3; //true
< Less than: true if the left operand is less than the right operand 3<2; //false
<= Less than or equal to: true if the left operand is less than or equal to the right operand 2<=2; //true

Example 1: Equal to Operator

const a = 5, b = 2, c = 'hello'; // equal to operator console.log(a == 5); // true console.log(b == '2'); // true console.log(c == 'Hello'); // false

== evaluates to true if the operands are equal.

Note: In JavaScript, == is a comparison operator, whereas = is an assignment operator. If you mistakenly use = instead of ==, you might get unwanted result.

Example 2: Not Equal to Operator

const a = 3, b = 'hello'; // not equal operator console.log(a != 2); // true console.log(b != 'Hello'); // true

!= evaluates to true if the operands are not equal.

Example 3: Strict Equal to Operator

const a = 2; // strict equal operator console.log(a === 2); // true console.log(a === '2'); // false

=== evaluates totrue if the operands are equal and of the same type. Here 2 and '2' are the same numbers but the data type is different. And === also checks for the data type while comparing.

Note: The difference between == and === is that:

== evaluates to true if the operands are equal, however, === evaluates to true only if the operands are equal and of the same type

Example 4: Strict Not Equal to Operator

const a = 2, b = 'hello'; // strict not equal operator console.log(a !== 2); // false console.log(a !== '2'); // true console.log(b !== 'Hello'); // true

!== evaluates to true if the operands are strictly not equal. It's the complete opposite of strictly equal ===.

In the above example, 2 != '2' gives true. It's because their types are different even though they have the same value.

Example 5: Greater than Operator

const a = 3; // greater than operator console.log(a > 2); // true

> evaluates to true if the left operand is greater than the right operand.

Example 6: Greater than or Equal to Operator

const a = 3; // greater than or equal operator console.log(a >= 3); //true

>= evaluates to true if the left operand is greater than or equal to the right operand.

Example 7: Less than Operator

const a = 3, b = 2; // less than operator console.log(a < 2); // false console.log(b < 3); // true

< evaluates to true if the left operand is less than the right operand.

Example 8: Less than or Equal to Operator

const a = 2; // less than or equal operator console.log(a <= 3) // true console.log(a <= 2); // true

<= evaluates to true if the left operand is less than or equal to the right operand.

JavaScript Logical Operators

Logical operators perform logical operations: AND, OR and NOT.

Operator Description Example
&& Logical AND: true if both the operands/boolean values are true, else evaluates to false true && false; // false
|| Logical OR: true if either of the operands/boolean values is true. evaluates to false if both are false true || false; // true
! Logical NOT: true if the operand is false and vice-versa. !true; // false

Example 9: Logical AND Operator

const a = true, b = false; const c = 4; // logical AND console.log(a && a); // true console.log(a && b); // false console.log((c > 2) && (c < 2)); // false

&& evaluates to true if both the operands are true, else evaluates to false.

Note: You can also use logical operators with numbers. In JavaScript, 0 is false and all non-zero values are true.

Example 10: Logical OR Operator

const a = true, b = false, c = 4; // logical OR console.log(a || b); // true console.log(b || b); // false console.log((c>2) || (c<2)); // true

|| evaluates to true if either of the operands is true. If both operands are false, the result is false.

Example 11: Logical NOT Operator

const a = true, b = false; // logical NOT console.log(!a); // false console.log(!b); // true

! evaluates to true if the operand is false and vice-versa.

Eu tenho que escrever um teste de unidade para uma função JavaScript para comparar dois números de telefone. Esta é uma função cujos parâmetros de entrada são duas strings e o tipo de retorno é true / false . True Se os números de telefone forem os mesmos, false se não for. Tantos casos quanto possível devem ser incluídos no teste.

Definição de função é phoneNrsAreEqual(nr1: String, nr2: String): Bool

Obrigado por me ajudar!

The equality operators (== and !=) use the IsLooselyEqual Abstract Operation to compare two operands. This can be roughly summarized as follows:

  1. If the operands have the same type, they are compared as follows:
    • Object: return true only if both operands reference the same object.
    • String: return true only if both operands have the same characters in the same order.
    • Number: return true only if both operands have the same value. +0 and -0 are treated as the same value. If either operand is NaN, return false; so, NaN is never equal to NaN.
    • Boolean: return true only if operands are both true or both false.
    • BigInt: return true only if both operands have the same value.
    • Symbol: return true only if both operands reference the same symbol.
  2. If one of the operands is null or undefined, the other must also be null or undefined to return true. Otherwise return false.
  3. If one of the operands is an object and the other is a primitive, convert the object to a primitive using the object's @@toPrimitive() (with "default" as hint), valueOf(), and toString() methods, in that order. (This primitive conversion is the same as the one used in addition.)
  4. At this step, both operands are converted to primitives (one of String, Number, Boolean, Symbol, and BigInt). The rest of the conversion is done case-by-case.
    • If they are of the same type, compare them using step 1.
    • If one of the operands is a Symbol but the other is not, return false.
    • If one of the operands is a Boolean but the other is not, convert the boolean to a number: true is converted to 1, and false is converted to 0. Then compare the two operands loosely again.
    • Number to String: convert the string to a Number using the same algorithm as the Number() constructor. Conversion failure would result in NaN, which will guarantee the equality to be false.
    • Number to BigInt: compare by their numeric value. If the number is ±Infinity or NaN, return false.
    • String to BigInt: convert the string to a BigInt using the same algorithm as the BigInt() constructor. If conversion fails, return false.

Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions).

The most notable difference between this operator and the strict equality (===) operator is that the strict equality operator does not attempt type conversion. Instead, the strict equality operator always considers operands of different types to be different. The strict equality operator essentially carries out only step 1, and then returns false for all other cases.

There's a "willful violation" of the above algorithm: if one of the operands is document.all, it is treated as if it's undefined. This means that document.all == null is true, but document.all === undefined && document.all === null is false.

O valor passado como primeiro parâmetro é convertido para um valor boleano, se necessário. Se o valor é omitido ou é 0, -0, null, false, NaN, undefined ou é uma string vazia(""), o objeto terá um valor inicial de false. Todos outros valores, incluindo qualquer objeto ou string "false",  criam um objeto com valor inicial  true.

Não confunda os valores primitivos Boolean true e false com os valores true and false do objeto Boolean.

Qualquer objeto cujo o valor não é undefined ou null, incluindo um objeto Boolean que o valor seja false, é avaliado para true quando passa por uma declaração condicional. Por exemplo, a condição a seguir if a declaração é avaliada como true:

var x = new Boolean(false); if (x) { }

Esse comportamento não se aplica aos primitivos Boolean. Por exemplo, a condição a seguir if a declaração é avaliada como false:

var x = false; if (x) { }

Não use um objeto Boolean para converter um valor não-boleano para um valor boleano. Ao invés disso use Boolean como uma função para executar essa tarefa:

var x = Boolean(expression); var x = new Boolean(expression);

Se você especificar qualquer objeto, incluindo um objeto Boolean cujo valor é false, como valor inicial de um objeto Boolean, o novo objeto Boolean terá o valor de true.

var myFalse = new Boolean(false); var g = new Boolean(myFalse); var myString = new String('Hello'); var s = new Boolean(myString);

Não use um um objeto Boolean no lugar de um primitivo Boolean.