# Conditional logic: JavaScript for Beginners

A fast outline of comparison operators and how to develop an if statement.

On the off chance that statements are normally utilized in JavaScript for conditional logic and can be pretty much as basic or intricate as required.

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

### Conditions

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

``````// a greater than b
(a > b)
// a less than b
(a < b)
// a equal to b
(a = b)
// a equal to b (strict version)
(a === b)
// a not equal to b
(a != b)
// a greater than or equal to b
(a >= b)
// a less than or equal to b
(a <= b)
// a greater than b or c less thand d
(a > b || c < d)
// a greater than b and c less than d
(a > b && c < d)
``````

### If statement

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

``````const age = 16;

if (age >= 13) {
console.log('You are a teen🤩');
}
// you canassign a condition to variable
const isTeen = age >= 13;

if (isTeen) {
console.log("You are a teen🤩");
}
``````

### Else clause

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

``````cons tage = 16;

if (age >= 18) {
} else {
/*
if the condition isn't met so the else action will be executed instead
*/
console.log("Hey kiddo😁");
}
``````

### Several conditions

You can add multiple conditions if needed.

``````const age = 10;

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

console.log(message);
``````

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;

console.log(message);

``````

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

### Several conditions

Use an else if clause to check against several conditions.

``````const age = 14;

if (age >= 18) {
} else if (age < 18 && >= 13) {
/*
the first condition isn't met but this second else, if is so this action, will be executed
*/

console.log("You are a teenager");
} else {
console.log("Hey kiddo😁");
}
``````

## Wrapping

• Use an if statement to act only if the condition is met
• Add an else clause to perform a different action when the condition isn't met
• 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