Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Conditionals (else)
When we write a conditional statement, the code inside the curly braces only runs if the condition is true
.
But what if the condition is false
? We can write code to handle that scenario as well.
Try this code in the editor:
if (true === false) { "true is equal to false"; } else { "true is not equal to false"; }
The else
keyword can follow up from an if
statement and run code if the condition is not met.
Multiple if
Conditions
We can actually create a chain of conditions to check. Run this code in the editor:
if (1 > 2) { "1 is greater than 2"; } else if (1 < 2) { "1 is less than 2"; } else { "1 is equal to 2"; }
The else if
statement can follow up from an if
statement, just like a regular else
statement can. However, the else if
statement has its own condition to check. It will only run if its own condition is true
.
Try changing the example to get different sections of code to run.
Conditions in a Function
Let's see what a conditional statement looks like inside a function. Now we have arguments to work with, like input
below. input
could be any value.
This function will return true
if input
is either true
or false
. If input
is any other value, false
is returned.
Try calling the function with different values to get different results:
function checkIfTrueOrFalse(input) { if (input === true) { return true; } else if (input === false) { return true; } else { return false; } } checkIfTrueOrFalse(17);
Learning Goals
I know what an
else
statement isI know how to chain multiple conditions with
else if
statementsI can use a conditional statement inside a function
Code Editor
Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.
Console Output
0 output lines