JavaScript is able to make decisions based on data. It can run code only when certain conditions are met.
To do this, we use conditional statements. A conditional statement checks a condition, and if it is true, executes some code.
Run these examples in the editor:
if (true) {
console.log("code between the {} will run");
}
if (false) {
console.log("this code will NOT run");
}
The first example logs a message to the console, showing us that the code inside the curly braces executed.
The second conditional statement does not execute because the if
condition was false
. Only values that resolve to true
will execute. The second console.log
will not execute, so it won't log anything to the console.
Using if
with a Comparison Operator
Now try this example:
if (1 === 2) {
console.log("does this code run?");
}
Nothing is logged to the console. Since the if
condition wasn't met, the code between the curly braces didn't run.
Change the condition from 1 === 2
to 1 !== 2
and run it again.
This time we should see a message logged to the console. Since 1 !== 2
resolves to true
, the code between the curly braces was executed.
Using if
in a Function
This is an example of using an if
statement in a function:
function isDivisibleBy5(number) {
if (number % 5 === 0) {
return true;
}
return false;
}
isDivisibleBy5(20);
Try running the function with different arguments to get different results.
Notice how the return
statement ends the function immediately. When the function returns true
, it stops executing. This behavior means a function will never return two values.