IF/Else in JavaScript

Keesha Hargrove
2 min readDec 9, 2021

To create a program that can make decisions, you can use the JavaScript if…else statement.

Here are three forms of the if…else statement.

if statement

if…else statement

if…else if…else statement

As a JavaScript statement, the if statement is probably one of the most commonly used. As long as a condition is met, an if statement or block of code will be executed.

{ The if statement evaluates the condition inside the parenthesis ().

If the condition is evaluated to true, the code inside the body of if is executed.

If the condition is evaluated to false, the code inside the body of if is skipped. }

A conditional statement like ‘else if’ specifies if a different decision should be made or not. Conditions determine what action the statement takes.

This will illustrate the if statement:

let x = 100;
if( x > 50 )
console.log('x is greater than 50');

This sets the variable x to 100. The x > 50 expression evaluates to true, therefore the script shows a message in the console window.

Curly braces should be used for multiple statements if you have more than one to execute.

if( condition ) {
// statements
}

Let look more into if/else

let x = 25;
if (x > 10) {
console.log('x is bigger than 10');
} else {
console.log('x is smaller than or equal 10');
}

This is another way to chain the if else statements:

if (condition_1) {
// statements
} else if (condition_2) {
// statements
} else {
// statements
}

Conclusion

When JavaScript if else statements are used, we can decide which code in a program should be run depending on a number of factors. Conditional statements are used in all programming languages to provide logic to the code in some way.

--

--