Note:
This is part of control flow which I forgot to mention and would like to add on to that with it's own explaination. Check out the control flow blog HERE
What is Logical Operators?
A logical operators job is simply connect two or more programming statements to return true
or false
.
Three logical operators are:
AND && | Return true if both operands are true.
OR || | Return true if either operand is true.
NOT ! | Return true if operand is false.
Let say I want to evaluate if user password is long enough and have special character #
, I can use &&
to evaluate like this:
const password = "#passwordislong";
if (password.length >= 10 && password.includes('#')) {
console.log('very strong');
} else if (password.length >= 8) {
console.log('strong');
} else {
console.log('weak');
}
Above, the password is more than 10 character long and has a special character # so it safe to say the password is 'very strong'.
Now, what if I want to include ||
to else if statement so if the password length is 8 character or more or password length is greater or equal to 5 with special character #
for example.
if (password.length >= 10 && password.includes('#')) {
console.log('Very strong');
} else if (
password.length >= 8 ||
(password.length >= 5 && password.includes('#'))
) {
console.log('strong');
} else {
console.log('weak');
}
The else if take in two condition. If the password length is greater or equal to 8 or password length is greater or equal to 5 and it include '@', then the statement is true and the password is 'strong'
Last operator I will analyze is !
or "Logical Not".
Logical not operator return something true to false and vice versa .
Example:
In normal behavior, the if statement only run the code block only if what it's evaluated inside is true.
//Let's evaluate if there's an item
let item = false;
if (item) {
console.log('run something');
}
//output: Nothing since item is false, the code block will not run
But if I add the logical not !
in front of the item, it switch it to true and the code now run without changing the value item which will always be false.
//If we add ! to item
let item = false
const item = false;
if (!item) {
console.log('run something');
}
//output: 'run something'
There we go! It is important for me to understand logical operators since it is the building block of control flow. Using this will help me develop and evaluate statements effectively.
Top comments (0)