Conditional Statement in Javascript Basics

Giwon
2 min readJun 11, 2023

--

Let's say you have certain conditions for your outcome in Javascript. You would compare the result of two or more inputs and create a specific output.

For example, you want to categorize people who are legal to drink and those who are not.

First, the basic layout would be the following, provided by an example.

if statement layout in javascript
const age = 28 

if (age >= 21) {
console.log('This person can drink')
} else {
console.log('This person cannot drink')
}

The following example would be a basic “if… else” statement by setting a condition of “if the value of age is greater or equal to 21, then output (‘This person can drink’). If not, output (‘This person cannot drink’).

By simply stating, “else” in the conditional statement, it tells Javascript that if the value of age is NOT the corresponding condition, then just simply output (‘This person cannot drink’), no matter what age is.

if

age is greater or equal to 21

else

age is NOT greater or equal to 21

Then what does “if else” mean?

By stating “if else (condition)” you tell Javascript, you want to set multiple conditions. For example, if the age is under 13, you want to output “DEFINITELY NOT DRINKING AGE”. Meanwhile, you also want to keep the (‘This person can drink’) and ‘This person cannot drink’) conditions at the same time.

You would write it in the following:

const age = 28 

if (age >= 21) {
console.log('This person can drink')
} else if (age < 13 ){
console.log('DEFINITELY NOT DRINKING AGE')
} else {
console.log('This person cannot drink')
}

By stating “if… else if… else” You tell Javascript to check the first condition of if age is greater than equal to 21. If age is greater than 21, then it stops with (‘This person can drink’). If not, it moves on to the next condition if age is less than 13. Once again, if age is less than 13, then it stops here. Otherwise, the output would be “This person cannot drink”.

--

--