User Tools

Site Tools


programming:conditional_statements_js

Conditional Statements

If Statements

If statements allow your code to make decisions based on something. For example, If it is raining, bring an umbrella, else, wear shorts.

Example:

if(condition){
    //code here runs if condition is true
}
else{ 
    //code runs here if the condition was not true
}

You can also add more than one if by using an else if. The program will go in order they are written and stop once it finds one that is true, or gets to the else statement. It is important to note 2 things

You do not need an else statement, the program will just skip the code if there are no true if’s

The code will stop at the first true if/else if, and will not run any of the preceding ifs in the block of code

if(condition 1){
	//if condition 1 is true, run this code
}
else if(condition 2){
	//if condition 1 is false, and condition 2 is true, run this code
}
else{
	//if condition 1 and condition 2 are false, run this code
}

//also valid

if(condition 1){
	//if condition 1 is true, run this code
}
else if(condition 2){
	//if condition 1 is false, and condition 2 is true, run this code
}
//nothing is run if if condition 1 and condition 2 are false
programming/conditional_statements_js.txt · Last modified: 2020/10/06 19:34 by shapirofrosts