Logical Operators in JavaScript

Author
By Darío Rivera
Posted On in Javascript

Logical operators in JavaScript are usually used in operations with boolean values. However, they can return other values depending on the values being compared. In this post we will see everything about logical operators.

AND

This operator returns true when used with boolean values if and only if all its operands are true. Example:

true && true;    //true
(5 > 7) && (6 < 10) && (4 >= 10);    // false

When used in conjunction with non-boolean values, it returns the first element that can be converted to false. This conversion is the same as used in the IF block (Common Conversions). Example:

0 && 'bar';    // 0
true && true && '';    // ''

Since an empty string ('') is parsed as false, it is returned at the end of the comparison. If no parameter is true, the last operand is returned.

OR

This operator returns true when any of its operands is true. Example:

true || false;   // true
false || false;   // false

When used in conjunction with non-boolean values, it returns the first element that can be converted to true. This conversion is the same as used in the IF block (Common Conversions). Example:

1 || false;    // 1
false || '' || [1,2];    // [1,2]

Since an empty string ('') is parsed as false, [1,2] is returned. If no parameter is true, the last operand is returned.

NOT

Returns false for a simple operand that can be converted to true (Common Conversions). Otherwise, this operator returns true.

!true;    // false
![];    // false
!'';    // true

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.