DEV Community

Danish Saleem
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
Enter fullscreen mode Exit fullscreen mode

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) {
  console.log("You are an adult");
}

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

if (isAdult) {
  console.log("You are an adult");
}
Enter fullscreen mode Exit fullscreen mode

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) {
  console.log("You are an adult");
} else {
  console.log("You are not an adult");
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;

const message = age >= 18 ? "Adult" : "Not Adult";

console.log(message); // Output: Adult
Enter fullscreen mode Exit fullscreen mode

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 💜

You can follow me on Twitter, Instagram & GitHub

If you like this post. Kindly support me by Buying Me a Coffee

Buy Me a Coffee

Discussion (0)