If Statements (Conditionals)
What is an if
statement?
An if statement allows you to run some code ONLY if the condition provided is
true
.
var someCondition = true;
if (someCondition) {
// instructions in this block will run when SOME_CONDITION evaluates to "true"
}
if (true) {
// not very useful, since this will ALWAYS be true
}
Comparison operators
When evaluating the truth
of a condition, it’s often helpful to compare to
values. That’s where we use comparison operators
.
// < > <= >= == ===
if (3>5) {} // greater than
if (3<5) {} // less than
if (3>=5) {} // greater than OR equal to
if (3<=5) {} // less than OR equal to
if (3=='3') {} // equality. Returns true
// -> true
if (3==='3') {} // strict equality. Includes type comparison.
// -> false
if (3!='3') {} // non-equality. Like opposite of `==`. If 3 is NOT equal '3'
// -> false
if (3!=='3') {} // non-strict equality. If 3 is NOT equal AND NOT same type as '3'
// -> true
===
is usually recommended over ==
.
else
and else if
Sometimes you want to check for multiple conditions when only 1 should be the
case.
// these conditions will be checked in order. When a condition is true,
// ONLY that block will run.
if (a>b) {
// do something if a is greater than b
} else if (a<b) {
// do something else if a is less than b
} else {
// do something else if neither of the above conditions are true
}
AND and OR
Want to combine 2 or more conditions?
Use the &&
AND operator, or the ||
OR operator.
if (a>5 && a<10) {} // is "a" greater than 5 AND less than 10?
if (a>5 || a>10) {} // is "a" greater than 5 OR is "a" greater than 10?
Exercises. Now you try it.
// 1. Add an additional check (try to use "else if") for "less than 5" and modify the result message
// when that happens
// 2. Add an "else" block for the condition that it is exactly 5 and modify the
// result message.
// 3. Test your logic by changing the input number.
var result;
var input = 7;
if (input > 5) {
result = "Input is bigger than 5!";
}
result