Boolean logic is like it’s own kind of weird math. Understanding how to get that weird math to do what you want is essential to writing conditions in JavaScript. Let’s talk about a some of the rules of boolean logic.
Operators
There are three main operators in boolean logic: And &&
, Or ||
and Not !
.
The And &&
operator returns true
if the left side AND the right side are true
.
Expression | Simplifies to |
true && true | true |
true && false | false |
false && true | false |
false && false | false |
The Or ||
operator return true
if the left side OR the right side are true
.
Expression | Simplifies to |
true || true | true |
true || false | true |
false || true | true |
false || false | false |
The Not !
operator flips true
to false
and flips false
to true
.
Expression | Simplifies to |
!true | false |
!false | true |
Order of Operations
When we have a boolean expression, like this one:
true && (false || true && !false)
The computer needs to know in what order to evaluate the operators.
Here is the Order of Operations for boolean logic:
- Parenthesis
()
- Not
!
- And
&&
- Or
||
Returning to our expression, that means that it will simplify in this order:
- Go inside the parenthesis first. Inside the parenthesis we again follow the Order of Operations.
true && (false || true && !false)
- Simplify the Not
!
operator inside the parenthesis.true && (false || true && true)
- Simplify the And
&&
operator inside the parenthesis.true && (false || true)
- Simplify the Or
||
operator inside the parenthesis.true && (true)
- Now that the parenthesis is simplified, we can simplify the And
&&
outside the parenthesis.true
Truthy and Falsy
In Javascript, everything is considered truthy or falsy. That means that if you treat any value like a boolean, it will act like one. This can be very useful!
There are only a few values that are falsy:
false
– the boolean value false (obviously)""
– an empty string0
– the number zero (importantly, negative numbers are NOT falsy)null
– something that’s been set to nullundefined
– something that has not been definedNaN
– not a number
Everything else is truthy.
For example, if you have code like this:
const age = null
if(!age) {
console.log("Error: That's not an age!")
}
When this code runs, the error message will be logged to the console. The same thing will happen if age is undefined
, 0
, NaN
, etc.
But if age
has a truthy value, like 12
, the if
condition will evaluate to false
and the error message will not be logged to the console.
Practice
Now that you know the rules, the best way to fully understand boolean logic is to practice with it!