Conditional
If/elif/else statement
We often perform a task based on a condition. For example, if the weather is nice today, then we will go outside. If the alarm clock rings, then we’ll shut it off. If we’re tired, then we’ll go to sleep. In programming, we can also perform a task based on a condition using an if/elseif/else statement:
let stopLight = 'yellow';
if (stopLight === 'red') {
console.log('Stop!');
} else if (stopLight === 'yellow') {
console.log('Slow down.');
} else if (stopLight === 'green') {
console.log('Go!');
} else {
console.log('Caution, unknown!');
}
Comparison Operators
Here is a list of some handy comparison operators and their syntax:
- Less than:
<
- Greater than:
>
- Less than or equal to:
<=
- Greater than or equal to:
>=
- Is equal to:
===
- Is not equal to:
!==
Logical Operators
Working with conditionals means that we will be using Booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators:
- the and operator
&&
- the or operator
||
- the not operator, otherwise known as the bang operator
!
When we use the &&
operator, we are checking that two things are true:
if (stopLight === 'green' && pedestrians === 0) {
console.log('Go!');
} else {
console.log('Stop');
}
If we only care about either condition being true, we can use the ||
operator:
if (day === 'Saturday' || day === 'Sunday') {
console.log('Enjoy the weekend!');
} else {
console.log('Do some work.');
}
The !
not operator reverses, or negates, the value of a boolean: