## DEV Community is a community of 846,721 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Danish Saleem

Posted on • Updated on

# JavaScript for Beginners - Chapter 4: Conditional Logic

In any coding language you will often need to perform different actions based on certain conditions. In order to figure out which action to take you would use an if statement and in this quick tutorial we will look at different ways to correctly form an if statement.

## Comparisons

Before we do that though we should quickly cover some comparison operators.

``````a > b; // a is greater than b

a < b; // a is less than b

a == b; // a is equal to b

a === b; // a is equal to b (strict version)

a != b; // a is not equal to b

a !== b; // a is not equal to b (strict version)

a >= b; // a is greater than b or is equal to b

a <= b; // a is less than b or is equal to b

a > b || c < d; // a is greater than b OR c is less than d

a > b && c < d; // a is greater than b AND c is less than d
``````

## If Statement

This is the most basic if statement. If the condition is true then the action inside the statement is carried out, if the condition isn't true then nothing will happen.

``````const age = 20;

if (age >= 10) {
}

// You can assign a condition to a variable
const isAdult = age >= 10;

}
``````

## Else Clause

Alternatively, we can specify for something else to happen when the condition isn't met by using the else clause.

``````const age = 16;

if (age >= 18) {
} else {
}
``````

### Several Conditions

You can add multiple conditions if needed.

``````const age = 10;

const message =
age >= 18 ? "Adult" : age >= 13 && age < 18 ? "Teenager" : "Child";

console.log(message); // Output: Child
``````

Top Tip: I would advise not to use the shorthand with several conditions as it starts to look less structured and can make your code difficult to maintain.

## Conditional Operator

You can also use the question mark operator to write a shorthand if statement.

``````const age = 20;

``````

Use this shorthand for simple logic since anything too complex will make it difficult to read and understand.

### Summary

• Use an if statement to perform an action only if the condition is true.
• Add an else clause to perform a different action when the condition isn't true.
• For several conditions include an else if clause.
• The question mark operator can be used for shorthand if statements.
• Only use the shorthand for simple logic to maintain code readability.

### Let's connect 💜 