Learn about Logical Operators in JavaScript

0
1438
javascript-logical-operators-740X296

javascript-logical-operators-740X296

Logical operators include ‘&&'(AND), ‘||’ (OR) and ‘!'(is NOT). They are used in conditional statements – statements which give the green light for actions to be performed only under certain circumstances. The action/s will be performed only if the statement equals to the Boolean

value of TRUE.
|| – the condition/s must be TRUE on at least one side of this operator in order for the whole statement to yield TRUE.
&& – the conditions on both sides of this operator must be TRUE in order for the whole statement to yield TRUE.
! – Yields true if the value attached to it is equal to FALSE.

Let’s learn how they work by demonstrating their functionality:

The OR operator:

The EQUALS operator:

The is NOT operator:

The AND opertor:

1

A working example of the && operator:

outcome:
2

Explanation: the code first checks if David is under or equal to 4 AND smaller than 13. if both conditions are met, it carries out the actions inside the following ‘{}’. otherwise (if the outcome is FALSE, which it is in our case), it goes to the next conditional statement, and checks if David is bigger than or equal to 13 AND smaller than 20. if both conditions are met, it carries out the actions inside the following ‘{}’. otherwise (FALSE outcome, like in this specific case), it goes to the next conditional statement, and checks if david is bigger than or equal to 20 AND smaller than 65. In our case, 42 is bigger than 20 AND smaller than 65 (both sides of the && yield TRUE), so the actions inside the following ‘{}’ are carried out.

Working example of OR:

Another way to perform logical conditions is with the ternary operator, like so:
(condition) ? Do if TRUE : Do if FALSE;

The ternary operator starts with a condition followed by a question mark. If the condition is TRUE, the actions immediately following the question mark will be performed (or the value will be assigned). Otherwise, the actions on the other (right) side of the “:” will be performed (or the value will be assigned).

https://blogeduonix-2f3a.kxcdn.com/wp-content/uploads/2015/10/Learn-Javascript-And-JQuery-From-Scratch.png

A working example:

In this case, the variable canIdrive will get the value of TRUE if it’s bigger than or equal to 17, otherwise it will get the value of FALSE.
3

To summarize, we’ve seen Javascript logical operators in action. We use the logical operators to check if multiple conditions are TRUE or FALSE (i.e., check the value of more than one variable or check if several conditions apply to the same variable) . They are are extremely useful inside if/else as well as while statements, and simple to use. That’s all for today, See you in next tutorial on JavaScript till then keep learning

LEAVE A REPLY

Please enter your comment!
Please enter your name here