Basics of If, Else and Else If statements

Daniel BrobäckDaniel Brobäck
2 min read

In Javascript, there are multiple ways to write conditionals. The first way most new developers get introduced to and get comfortable with is the “if statement”, “else statement” and the “else if” statement.

Hi 👋 and welcome to the first part of the mini-series of conditionals in JavaScript. We will begin with the fundamentals and build on top of it, let's get started!

"If" statements

Where if the condition is fufilled and true: It will executes a specific block of code.

Example:


const  numberOfApples = 5;
if (numberOfApples == 5) {
    console.log('You got 5 apples');
}

/* since the numberOfApples variable is set to 5, 
the "if" statement gets executed and prints out the console.log. */

"Else" statements

When the "if" statement is false, the the block of code after the "else" statement gets executed if the condition is false. It works as a fallback for the "if" statement.


const income = 4999;
if(income > 5000) {
console.log('High income');
}else{
console.log('Low income');
}

/* Since the condition of the "if" statement wasn't met, 
the "else" statement gets executed instead. */

"Else if" statements

Specifies a new test if the "if" condition is false

 const carBrand = "bmw";
  if (carBrand == "You drive a Volvo") {
    console.log("volvo");
  } else if (carBrand == "bmw") {
    console.log("You drive a BMW");
  } else {
    console.log("You drive a car of another brand");
  }

/* in this example the brand of the car is checked. 
Since carBrand is set to the string of “BMW”  the first if statement is false. 
So javascript tries the Else if and tests that condition is true, 
and it is! So the string “You drive a BMW” is logged to the console. */

Good to know is that "if" and "else if" statements don't need an "else" statement to execute. If none of the conditions passes, then javascript simply moves on and doesn't execute any of the conditional blocks of code.

Thanks for reading this far, you should now have a good understanding of how to use basic conditional statements in your projects and applications. Next up: Comparison operators. See you in the next post!

Liked what you read? Great, give me a thumbs up! 🚀

Want to connect/give feedback? Awesome, write a comment below! 🏆

0
Subscribe to my newsletter

Read articles from Daniel Brobäck directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Daniel Brobäck
Daniel Brobäck

I'm a Front-end Developer specialized in JavaScript and React. Sharing my notes and knowledge hoping I help this fantastic community! 🥳