In JavaScript things can either be true
or false
. Often we want to perform some code based on weather a condition
is true
or false
.
// Pretend code
if TRUE do THIS
otherwise do THAT
Let's look at common truthy
values:
- The Boolean true -
true
- A non empty String -
'hi'
,'a'
- A non zero Number -
-4
,50
,10045
,1
- Any Array -
[0, 1, 2]
,['a']
,[]
- Any Object -
{}
,{ name: 'bobby' }
Let's look at common falsey
values:
- The Boolean false -
false
- The number 0 -
0
- An empty String -
''
NaN
null
undefined
Often in your code you need to test multiple things and act on them based on the following:
- At least one of the things is true/false
- If ALL of the things are true/false
To do this, we use AND
and OR
logic gates:
A | B | RESULT |
---|---|---|
0 | 0 | FALSE |
1 | 0 | FALSE |
0 | 1 | FALSE |
1 | 1 | TRUE |
A | B | RESULT |
---|---|---|
0 | 0 | FALSE |
1 | 0 | TRUE |
0 | 1 | TRUE |
1 | 1 | TRUE |
It is possible to use as many parameters as you want to test, but it starts to get very difficult to follow after 3.
A special symbol in JavaScript and most other programming languages is the NOT
symbol. This is the exclamation mark !
A | RESULT |
---|---|
0 | TRUE |
1 | FALSE |
You can take anything and convert it to a simple true
false
boolean value by using the special JavaScript symbol !!
(two exclamation marks).
Running this on the number 42: !!42
will become the Boolean true
Running this on the number 0: !!0
will become the Boolean false