Hey Amazing people
Welcome to another blog in the JavaScript blog course.|
In this blog, we aimed to study the Logical Operators of javascript.
Logical operators
There are four logical operators in JavaScript:
||
(OR)
&&
(AND)
!
(NOT)
??
(Nullish Coalescing)
Let's cover them in detail
|| (OR)
This is represented by 2 vertical lines.
result = a || b;
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
.
There are 2 raised to power n operations possible. n = number of variables.
alert( 1 || 1 ); // true
alert( 0 || 1 ); // true
alert( 1 || 0 ); // true
alert( 0 || 0 ); // false
As we see, true
this is the answer even if one is true(1).
You can understand OR as an add operator i.e. 1+0=1. etc.
OR only needs one value to be true and ultimately whole value becomes true.
Let's take an example
result = a || b || c
Now if any of one ( a or b or c ) is true, the whole result is true
and will not only depend on the other 2
&& (AND)
The AND operator is represented with two ampersands &&
:
result = a && b;
In classical programming, AND returns true
if both operands are truthy and false
otherwise:
alert( true && true ); // true
alert( false && true ); // false
alert( true && false ); // false
alert( false && false ); // false
An example with if
:
let hour = 12;
let minute = 30;
if (hour == 12 && minute == 30) {
alert( 'The time is 12:30' );
}
Just as with OR, any value is allowed as an operand of AND:
if (1 && 0) { // evaluated as true && false
alert( "won't work, because the result is falsy" );
}
On the contrary, it needs all values to be true to be true, and even if one value is false, the result would be false.
Let's take an example
result = a && b && c
Now if any of one ( a and b and c ) is false, the whole result is false
and needs all values to be true.
! (NOT)
The boolean NOT operator is denoted by the exclamation mark!
The syntax is straightforward:
answer = !value
if value is true
we would get false
and vice-versa.
The operator takes a single argument and performs the following actions:
The operand is converted to a boolean type: true/false. The inverse value is returned.
A resounding NO!! is occasionally used to convert a value to a boolean type:
alert( !!"non-empty string" ); // true
alert( !!null ); // false
That is, the first NOT changes the value to boolean and returns the opposite, followed by the second NOT. Finally, we have a simple value-to-boolean conversion.
A built-in Boolean function can achieve the same thing in a slightly more verbose manner:
alert( Boolean("non-empty string") ); // true
alert( Boolean(null) ); // false
Hope you loved this blog!!❣️
Follow the blog and support this blog.