DEV Community

grant-ours
grant-ours

Posted on

Taking a Look at Conditional Statements

if, else, and else if

When you're writing code and you want to perform different actions based on different decisions. This is where if statements come in handy!

if Statements

  • Use an if statement to run a specified block of code if a certain condition is true.

Example Structure of an if statement

if (condition) {
   // insert code here to be executed if the condition is true
}
Enter fullscreen mode Exit fullscreen mode

else Statements

  • Use an else statement to run a specified block of code if the condition is false.

Example Structure of an else statement

if (condition) {
   // insert code here to be executed if the condition is true
}else{
   // insert code here to be executed if the condition is false
}
Enter fullscreen mode Exit fullscreen mode

else if Statements

  • Use an else if statement to add a second condition if the first condition is false.

Example Structure of an else statement

if (1st condition) {
   // insert code here to be executed if the condition is true
} else if (2nd condition) {
   // insert code here to be executed if the first condition is false and the second condition is true
} else {
   // insert code here to be executed if the first condition is false and the second condition is false
}
Enter fullscreen mode Exit fullscreen mode

Pro Tip: Use console.log through out the process to figure out what is happening in your program and where!

Top comments (0)