Logical Operator

Sonu kumar
2 min readAug 16, 2020

--

There are three logical operators in JavaScript: | |(OR), && (AND), ! (NOT).

Although they are called “logical”, they can be applied to values of any type, not only boolean. Their result can also be of any type.

| | (OR)

The “OR” operator is represented with two vertical line symbols:

In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true, it returns true, otherwise it returns false.

In JavaScript, the operator is a little bit trickier and more powerful. But first, let’s see what happens with boolean values.

There are four possible logical combinations

alert( true || true ); // true

alert( false || true ); // true

alert( true || false ); // true

alert( false || false ); // false

As we can see, the result is always true except for the case when both operands are false.

If an operand is not a boolean, it’s converted to a boolean for the evaluation.

OR (| |) finds the first truthy values

OR (| |) opeartor search for first truthy values . For each operand, converts it to boolean. If the result is true, stops and returns the original value of that operand. If all the values compared are Falsy then it will return the last falsy value.

AND (&&)

The AND operator is represented with two ampersands &&:

In classical programming, AND returns true if both operands are truthy and false otherwise: Just as with OR, any value is allowed as an operand of AND:

AND (&&) finds the first falsy values

AND (&&) opeartor search for first falsy values . For each operand, converts it to boolean. If the result is true, stops and returns the original value of that operand. If all the values compared are truthy then it will return the last truthy value. In other words, AND returns the first falsy value or the last value if none were found.

! (NOT)

The boolean NOT operator is represented with an exclamation sign !.

The operator accepts a single argument and convert it into boolean and then it inverse the output. The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && or | |.

A double NOT ! ! is sometimes used for converting a value to boolean type: That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion.

Twitter :- sonu_pandey2001

--

--