Conditional Statements
Use this article as a reference sheet for JavaScript conditional statements.
- Conditional statements (
if
,else if
, andelse
) execute code if a set of conditions are met.
It’s often helpful to think about conditional statements in spoken language:
“If condition A is true, let’s follow a set of instructions, otherwise, if it is false, let’s do something else.”
This sentence is the equivalent of the following JavaScript conditional statement:
if (A) {//do something} else {//do something else}
Now, let’s consider a conditional statement that actualy does something:
var inNortherHemisphere = true;var latitude = 40.7;if (latitude > 30 && inNorthernHemisphere) {console.log("It's cold in December!");} else {console.log("It's not cold in December!");}
In the example above, if a location has a latitude greater than 30 degrees and is in the Northern Hemisphere, then It's cold in December!
will be logged to the console. If either condition is false, then the string It's not cold in December!
will be logged to the console. Only one of the two strings will be logged to the console, but never both.
Conditional statements can also be used to check more than one condition:
var isPublicSchool = false;var inState = true;if (isPublicSchool && inState) {console.log('Student qualifies for in-state tuition.')} else if (isPublicSchool || inState){console.log('Student may qualify for financial support.')} else {console.log('Student does not qualify for financial support.')}
In the example above, the if
/else if
/else
statement is used to check each condition, one after another. If isPublicSchool
is true and inState
is true, then the first block of code will execute. Otherwise, if isPublicSchool
is true or inState
is true, then the second block of code will execute. If neither condition is true, then the final block of code will execute.
In a conditional statement, the first condition that evaluates to true is the only block of code that executes. In the example above, if the first condition is true, then its code block will execute, and no other condition will be checked. This is important to note, because it is common for multiple expressions in a conditional statement to pass.
You are not limited to checking two conditions. You may use the else if
keywords repeatedly to check as many conditions as you would like. For example, an if
/else if
/else if
/else if
/else if
/else
statement will check five conditions.
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full team