DEV Community

Tom Yotwongjai
Tom Yotwongjai

Posted on • Updated on

Logical Operators

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.
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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.

Thanks for reading !! :)

Feel free to leave any comment or feedback!

Discussion (0)