DEV Community

Cover image for CONDITIONAL STATEMENT
Sabitha
Sabitha

Posted on

CONDITIONAL STATEMENT

Conditinal statement in javascript

JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.

Types of Conditional Statements

if statement
if...else statement
if...else if...else statement
switch statement
ternary (conditional) operator

1. if Statement

We use an if statement when you want to check only a specific condition. ‘if’ is a JavaScript keyword that tells the JavaScript interpreter that you are about to use a conditional statement. The statements inside an if statement will only execute if the condition is true.

example

let age = 18;

if (age >= 18) {
  console.log("You are an adult.");
}

Enter fullscreen mode Exit fullscreen mode

2. if…else Statement

This is another method to produce the same output as with if statements and the ternary operator. We use if…else statements for this purpose. The interpreter checks if the condition is true. If yes, then the statements inside the if block is executed and if not, the else block is executed. Unlike in if statements as in the example above, we don’t need to specify any condition inside an else statement.

example

let age = 16;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

Enter fullscreen mode Exit fullscreen mode

3. Nested if…else Statements

This is a method to check multiple statements. But this is not always an ideal one. You should be very careful in using these statements. Nested if…else statements mean that there are if…else statements inside an if or an else statement.

example

let age = 20;

if (age >= 18) {
  if (age >= 60) {
    console.log("You are a senior citizen.");
  } else {
    console.log("You are an adult.");
  }
} else {
  console.log("You are a minor.");
}

Enter fullscreen mode Exit fullscreen mode

Reference:https://data-flair.training/blogs/javascript-conditional-statements/

https://www.geeksforgeeks.org/javascript/conditional-statements-in-javascript/

Top comments (0)