Logical Operators
Logical operators are used alter or combine expression together to create a complex condition. While logical operators are typically used boolean
values, in which they will return a boolean
value, they can be used with non-Boolean value.
There are three logical operators: AND (&&
), OR (||
), and NOT (!
).
The AND Operator
When using boolean values with the AND (&&
) operator, the value true
will be returned if both values are true
and the value false
will be returned if at least one value is false
. For non-boolean values, if the first value is truthy
than the second value will be returned, else the first value will be returned.
console.log(true && true) // true
console.log(true && false) // false
console.log(true && 3 < 4) // true
console.log(true && 4 < 3) // false
console.log('Cat' && true) // true
console.log('Cat' && false) // false
console.log('Cat' && 'Dog') // 'Dog'
console.log('' && true) // ''
The OR Operator
When using boolean values with the OR (||
) operator, the value true
will be returned if at least one value is true
and the value false
will be returned if both values are false
. For non-boolean values, if the first value is truthy
than the first value will be returned, else the second value will be returned.
console.log(true || true) // true
console.log(true || false) // true
console.log(false || 3 < 4) // true
console.log(false || 4 < 3) // false
console.log('Cat' || true) // 'Cat'
console.log('Cat' || 'Dog') // 'Cat'
console.log(false || 'Dog') // 'Dog'
console.log('' || true) // true
The NOT Operator
The NOT (!
) operator will return false
if the following expression is truthy
. Otherwise, it will return true
.
console.log(!true) // false
console.log(!false) // true
console.log(!(3 < 4)) // false
console.log(!(4 < 3)) // true
console.log(!'Cat') // false
console.log(!'') // true