Javascript Logical Operators
In this lesson, we will learn about Logical operators in JavaScript, to combine two or more conditions, which are necessary for working with conditional statements, return a boolean value, true
if the condition is correct or false
if the condition is incorrect.
And (&&)
You can check more than one condition using And (&&)
. Returns true
if all conditions are correct. Returns false
if one of the conditions is incorrect, because the entire expression will evaluate to false. Example:
console.log(6 > 4 && 6 > 5); // true
In this example it returns true
, because all conditions are true
. The first condition (6 > 4) is true because 6 is greater than 4. The second condition (6 > 5) is true because 6 is greater than 5.
console.log(6 > 4 && 5 > 5); // false
In this example, it returns false
because there is a true condition and an incorrect condition. The first condition (6 > 4) is true because 6 is greater than 4. The second condition (5 < 5) is false because 5 is equal to 5.
Or (||)
You can check more than one condition. Returns true
if all conditions are true or at least one condition is true. Returns false
if all conditions are false. Example:
console.log(2 > 5 || 3 > 5); // fasle
The first condition (2 > 5) is false because 2 is less than 5. The second condition (3 > 5) is false because 3 is less than 5. In this example, it returns false
, because all the conditions are false.
Not (!)
It reverses the boolean value. That is, it converts true
to false
, and false
to true
. Example:
console.log(!true); // false
In this example we convert true
to false
using the Not operator (!)
before the true value.
console.log(!false); // true
In this example we convert false
to true
using the Not operator (!)
before the false value. Example:
console.log(!(5 > 3)); // false
In this example, we find that the condition (3 < 5) is correct and returns true
, but because we used Not (!)
before this expression, it converted true to false.
Javascript treats any value as true or false.
The following values are considered false:
- false
- 0
- "" or '' (Empty string)
- null
- Undefined
- NaN
The following values are considered true:
- Everything else that is not falsy
- true
- '0' [0 in a string]
- 'false' [false in a string]
- [] (empty array)
- {} (empty object)
- function () {} (empty function)
Anything in a string is truthy, even a space.
Note: The AND operator (&&)
returns the first falsy value it encounters, or the last value if all are truthy.
Example:
console.log(0 && 10); // 0
In this example the result is 0 because it is the first false value.
Example:
console.log('John' && 'Jeff'); // Jeff
In this example Since both values are truthy, the last value ('Jeff') is returned.
Note: The OR operator (!)
returns the first truthy value it encounters, or the last value if all are falsy.
Example:
console.log(0 || 50 || 60); // 50
In this example the result is 50 because it is the first truthy value.