Using conditions in JavaScript is easy. Let’s get started.

How to Use Conditions in JavaScript

Like many other programming languages, conditional statements in JavaScript start with the if statement.

Here’s what its syntax looks like:

If the condition within the parenthesis is true, then your program will execute the actions within the curly brace.

The else statement then comes in if you want to avoid a blank output when the if condition returns a false result:

Note that else doesn’t accept a defined condition. Instead, it executes its designated actions only if a previous condition is false.

And if you want to check other conditions before you use an else, this is where the else if statement comes in handy. It’s similar to how you use conditional statements in Python. It’s an “elif” and not “else if” in Python, though.

To use the else if statement in JavaScript, the conditional syntax becomes:

you can also use as many else if statements as you want:

Now let’s see some practical examples that combine these conditional statements:

The example above executes the action within the else statement because the value of name isn’t MUO.

Now let’s see an example code that uses the three conditional statements.

The code below logs a greeting for the name at index zero only:

JavaScript Conditions With Ternary Operator

You can also declare JavaScript conditions using the ternary operator.

The general syntax looks like this:

The question mark (?) checks the validity of the condition. If this is true, it executes operation one. Otherwise, it heads over to operation two.

Here’s a practical example of how to use the ternary operator with an if-else statement:

And if you want to check more conditions using JavaScript ternary operator (similar to else if):

Here’s a rewrite of the last code snippet in the previous section using ternary operation:

Note: Although it’s straightforward, you might not want to use the ternary operation with nested conditions as it can confuse you. But it’s still a neat way to express conditional statements if you know your way around it.

Control Your JavaScript With Conditions

Like every other programming language, a mastery of conditional statements in JavaScript lets you perform limitless logical operations. Consequently, you’re in control of how your program behaves.

That said, whether you decide to use plain “if-else” statements or the ternary operation, ensure that your code is readable and easy to understand.