JavaScript IF statements - Part 1 - AND OR conditions
- Published on
- • 3 mins read•––– views
What are if statements?
Imagine taking a walk in the woods and hearing animal noises. Our mind will wonder, what could this animal be? Is it a cat, a dragon or a wolf? Your unconscious mind will decide, if it's a cat, I will find it and pet it. If it's a dragon or a wolf, I will return home.
That's what if statements
are.
In this example, we will check if the noise the animal makes is a meow
. If it something else, we will return home.
if (animalNoise === 'meow') {
console.log("I'm gonna find you and pet you!")
} else {
console.log("I'm going back home")
}
The code above will work and keep us safe, but there are other animals in the woods that are harmless. We need to think of other possibilities.
OR || condition
Do you like birds? I like birds. We cannot image woods without birds chirping, can we?
if(animalNoise === 'meow' || animalNoise === 'chirp' ){
console.log(
"I'll keep walking"
) else{
console.log("time to go home")
}
}
On this example, we use
OR
, which is written with||
. If theanimalNoise
ismeow
||
chirp
we will keep walking. if it's anything else, we will return home.
AND && condition
We heard a meow
and got excited. We decided to find that cat and pet the heck out of it. But, there is another problem we need to think of.
const currentTime = 5
if (animalNoise === 'meow' && currentTime < 6) {
console.log("I'm gonna find you and I'm gonna pet you!")
} else {
console.log("It's getting dark, I should return home")
}
On the above code we will check two conditions. If we hear a
meow
and&&
currentTime
is less than<
6
we will find that kitty.&&
meansAND
, so both conditions must be true otherwise we will return home.
AND && and OR || chained
Can we get into more detail? Yes we can. Enter mom.
const momCalled = false
if (animalNoise === 'meow' || (amimalNoise === 'chirp' && momCalled === false)) {
console.log('keep walking')
} else {
console.log('Gotta go back')
}
Here we chained
&&
||
together. If theanimalNoise
ismeow
||chirp
&&mom didn't call
we can keep walking. We can keep chaining different conditions but this should give us the overall idea.
Closing words
That's how our brains work. We sense information with our eyes, ears, touch and nose and guess what it could be. Our brain is a non-stop if else statement.
On part two, we will discover else if
and some other real life examples.