Hello World, in our previous post we learnt how to use the unary operators in JavaScript.
In this post, we will learn how you can use logical operators to make decision in your code.By the end of this post, you should be able to use the &&
,!
and ||
operators to make decisions in your code.
Let's get started.
What are Logical Operators?
Logical operators are very useful for comparing variables and taking some action based on the result of the comparison.
It allows developers to test for true
or false
values and do something based on the result.
- If an expresion is true, we do this, if not, we can do that.
Logical operators are mainly used with Boolean values ( true
or false
values) and return Boolean values.However, they can also be used on non-Boolean values, returning a non-Boolean value.
In this article, we take a look at three main logical operators in JavaScript:
-
||
(OR) -
&&
(AND) -
!
(NOT) Let's see the details
Using the Logical !
(NOT) operator.
In JavaScript, logical (NOT) operator is represented with an exclamation sign !
. It's major use case is to reverse the value of a boolean
The logical
!
operator turns atruthy
value to afalsy
value and vice versa
Syntax for Logical NOT !
let result = !value;
When you apply the !
operator to a boolean value, it will convert the operand into the boolean type (eithertrue
or false
) and returns the reverse value
- if the value of the operand is
true
, the!
operator will return the inverse of the value (false
) - if the value of the operand is
false
, the!
operator will return the inverse of the valuetrue
.
Let's see an example below:
let result = true;
let isLoggedIn = false ;
console.log(!result);
console.log(!isLoggedIn)
The output of the above will be
false
true
- The value of the
result
variable istrue
, so the!
operator will return the inverse oftrue
( which isfalse
). - The value of the
isLoggedIn
variable isfalse
, so the!
operator will return the inverse offalse
(which istrue
).
Applying the !
operator on non-boolean values
When you operate the !
on a non-boolean value, the !
operator will convert the given value to a boolean value and then negates it.
Let's see some examples
let firstName = "Emma"; /* Non boolean value */
console.log(!firstName)
The output will be
false
The value in the
firstName
variable is atruthy
value, meaning the value is consideredtrue
when passed through a boolean function ( all non-empty strings are considered true)The
!
operator will then negate the valuetrue
returningfalse
All values are considered truthy
except ""
, null
, undefined
, 0
, and NaN
, ""
, which are falsy
values. Because these values are false
, the !
operator will return the reverse which is true
when operated on them.
Let's see some examples
console.log(!undefined)
console.log(!null)
console.log(!0)
console.log(!NaN)
console.log(!"")
The output will be
true
true
true
true
true
Using Double negation (!!
)
When the double negation !!
is used in our code, we are essentially using the logical NOT operator (!
) twice to change a value to its boolean value.
Consider the example below:
let totalUsers = 20;
console.log(!!totalUsers) /* using the ! twice */
Let's investigate what is happening:
- The first
!
will return the boolean value of thetotalUsers
and negate it. - Because the value of
totalUsers
istrue
, the first!
will negatetrue
returningfalse
. - The second
!
then negates the result offalse
, (!false
), returning the real boolean value of thetotalUsers
variable.
The output will then be
true
In summary, we use the logical NOT (!
) operator to** return the inverse or reverse of a boolean value**. The !
operator works on a single operand.
Using the Logical AND (&&
) operator.
Another way of making decisions in programming is using the &&
operator.
The AND
&&
operator returnstrue
if both operands aretrue
, otherwise, it returnsfalse
Syntax for the &&
operator
let result = a && b
Let's see what happens when we apply the &&
operator to two boolean values a
, b
.
- if
a
has a value oftrue
andb
has a value oftrue
, thena && b
will betrue
- if
a
has a value oftrue
andb
has a value offalse
, thena && b
will befalse
- if
a
has a value offalse
andb
has a value offalse
, thena && b
will befalse
- if
a
has a value offalse
andb
has a value oftrue
, thena && b
will befalse
.
In simple terms:
console.log( true && true ); // true
console.log( false && true ); // false
console.log( true && false ); // false
console.log( false && false ); // false
Let use the &&
operator in a conditional like the if()
statement.
- We have learnt that if the first operand evaluates to be
true
and the second operand evaluates to betrue
, then using the&&
operator will returntrue
- With the
if(condition)
, if the expression (condition) inside the brackets()
returnstrue
, then the statement after it will be evaluated.
Let's put all together with an example
let age = 20;
let isLoggedIn = true;
if(age && isLoggedIn){
console.log("You can access this website")
}
The output will be
You can access this website
- The expression (age
&&
isLoggedIn) will returntrue
since both values aretruthy
- Since the expression evaluates to be
true
, the code inside the{}
will be executed. - However, should any of the operand be evaluated as
false
, the&&
operator will returnfalse
, making the result of the expressionfalse
and the statement below will not be executed.
The result of the
&&
operator will returntrue
if both values aretrue
otherwise it will returnfalse
.
Finding the first falsy value using multiple &&
Sometimes, we can use two or more &&
values in our code also known as a chain of &&
operators.
Consider the code below
let result = firstValue && secondValue && thirdValue;
The &&
operator will do the following:
- Evaluates the values from left to right.
- For each value, converts it to a boolean (true or false)
- If the result is
false
, it stops executing and returns the original value of the operand - However, if all the values have been evaluted to be true (i.e all were truthy), it returns the last value.
Meaning, the
&&
operator returns the first falsy value or the last value if no falsy value was found.
- A **truthy **value is a value which can be converted to be
true
- A **falsy **value is a value which can be converted to be
false
Let's see some examples
- What will be the result of the
&&
?
let isLoggedIn = false;
let age= 18
let country = "Ghana";
console.log(isLoggedIn && age && country);
The output will be
false
The
&&
operator returns the first falsy value. SinceisLogged
has a value offalse
the result of the expression above will befalse
.What will be the result of the
&&
?
let isActive = true;
let users = 0;
let browser = "Google chrome"
console.log(isActive && users && browser)
The output will be
0
- The
&&
operator returns the first falsy value. Since
users
has a value of0
( 0 is a falsy value), the output will be the value0
.What will be the result of this
&&
?
let status = "Active";
let tweets = 203;
let career = "Frontend developer";
console.log(status && tweets && career)
The output will be
Frontend developer
- The
&&
operator returs the last value if all the values are truthy. - The
career
variable holds atruthy
value, hence the last truthy value isFrontend developer
.
Short-circuit evaluation using the && operator.
The &&
operator is short-circuited. This means
- If the result of one value is found to be false, the
&&
operator stops **and **returns the original value of that falsy operand; it will not check any of the remaining operands.
Consider the pseudo code below
(some falsy expression) && anotherExpr
The
anotherExpr
part is never evaluated because the first operand (some falsy expression
) is evaluated asfalse
Even if the
anotherExpr
is a function, that function will never be called.
Consider the example below
function firstExpr(){
console.log("first expression");
return false;
}
function anotherExpr(){
console.log("Another expression");
return true;
}
console.log(firstExpr() && anotherExpr());
The output will be
first expression
false
Do you know why ?
- The call to
firstExpr()
logsfirst expression
and returns `false' - Because the
firstExpr()
returnsfalse
the&&
operator short-circuits, hence, theanotherExpr()
will not be called. - At any instance the expression is evaluated to be
false
, the rest of the expression will not be executed.
Using the logical OR ||
operator
JavaScript uses this symbol ||
to represent the OR operator.
You can apply the ||
operator on two values of any type.
Synxtax for the OR operator
let result = a || b;
Usually if
a
can be converted totrue
, we returna
, else, returnb
.
Consider using the ||
operator on two boolean values
- if
a
istrue
andb
istrue
, thena || b
will returntrue
- if
a
istrue
andb
isfalse
, thena || b
will returntrue
. - if
a
isfalse
andb
istrue
, thena || b
will returntrue
- if
a
isfalse
andb
isfalse
, thena|| b
will returnfalse
.
From the above, there are four possible combinations
`
console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false
`
The
||
operator returnsfalse
if both values arefalse
.
Most times, the ||
operator is used in an if
statement to test if any of the given condition is true. If any of them returns true
, the statement below will be executed.
Consider the code below:
`
let age = 20;
if(age == 18 || age > 18){
console.log("You can enter the club ")
}
`
The output will be
You can enter the club
Do you know why ?
- The expression
age == 18
is false, butage > 18
evaluates to betrue
. - Since one of the expression is
true
,we will basically haveif(true)
and the statement below can then be executed, given the outputYou can enter the club
.
You can pass more conditions to the if
statement.
Consider the code below;
`
let age = 20;
let hasRegistered = false;
if(hasRegistered || age == 18 || age > 18 ){
console.log("You can enter the club ")
}
`
- Because there is at least one
truthy
value in the expression (i.eage > 18
), the statement in the code block will be executed and the output will beYou can enter the club
.
Finding the first truthy value using the ||
operator.
Given multiple ||
values
let result = firstValue || secondValue || thirdValue
The ||
operator does the following :
- Checks the operands from left to right
- For each operand, converts it to boolean
- If the result is
true
, it stops and returns the original value of that operand. - If all operands have been evaluated, and were all false, it returns the last operand
- The value is returned in the original form, without the conversion.
In other words, a chain of OR || returns the first truthy value or the last one if no truthy value is found.
For instance:
let firstName = "";
let lastName = "";
let middleName = "Fordjour";
console.log(firstName || lastName || middleName || "Guest");
The output will be
Fordjour
- The first truthy value in the expression is
Fordjour
- If there were no truthy values, then the output will be
Guest
(returning the last value )
Short-circuit evaluation of ||
The ||
operator is short-circuited. It means if the first value evaluates to be true
, the ||
operator doesn't evaluate the second value
Consider the code below
let firstName = "Emmanuel"
console.log( "Hello ",firstName || "Guest");
The output will be
Hello Emmanuel
- the
firstName
value is a truthy value, hence theGuest
will not be evaluated.
Logical operator precedence
It is the order in which an operator is executed.
When we have mixed logical operators in an expression, the JavaScript engine will evaluate the operators based on this order
- Logical NOT(!)
- Logical AND (&&)
- Logical OR(||)
Quick Challenge
Test your understanding of logical operators.
What will be the result of the expression below ?
console.log( null || 2 && 3 || 4 );
Find out which of the console,log
's will be executed
What will the results of the expressions be inside if(...)?
if (-1 || 0) console.log( 'first' );
if (-1 && 0) console.log( 'second' );
if (null || -1 && 1) console.log( 'third' );
Comment your answer below.
In Summary
- The
!
operator negates a boolean value - The
&&
returnstrue
if **both **operands aretrue
- The
||
returnstrue
if **one **of the operands istrue
Kindly share on your social networks if you find the post valuable Written with love 😍 from 🇬🇭 Ghana.
Me daa se (Thank you)
Top comments (0)