DEV Community

Anees Abdul
Anees Abdul

Posted on

Conditional Statements in JavaScript:

What are Conditional Statements in JavaScript?

  • Conditional statements are used to make decisions in a program.

Conditional statements include:

  1. if
  2. if...else
  3. if...else if...else
  4. switch
  5. ternary (? :)

1. if Statement:

  • Executes code only if the condition is true
let age = 20;

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

Enter fullscreen mode Exit fullscreen mode

2. else Statement:

  • Use else to specify a code block to be executed if the same condition is false.
if (condition) {
  // code to execute if the condition is true
} else {
  // code to execute if the condition is false
}
Enter fullscreen mode Exit fullscreen mode

3. else if Statement:

  • Used to check multiple conditions
let marks = 75;

if (marks > 90) {
  console.log("Excellent");
} else if (marks > 60) {
  console.log("Good");
} else {
  console.log("Average");
}
Enter fullscreen mode Exit fullscreen mode

4. switch Statement:

  • Used to compare one value with multiple cases
let day = 2;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  default:
    console.log("Invalid");
}
Enter fullscreen mode Exit fullscreen mode
  1. Ternary Operator:
  • Short form of if-else
condition ? expression1 : expression2


If the value of age is < 18, 
set the value of text to "Minor", otherwise to "Adult":

let text = (age < 18) ? "Minor" : "Adult";

Enter fullscreen mode Exit fullscreen mode

Important Concepts of javascript is: Truthy Falsy:

  • In JavaScript, every value is treated as either true or false when used inside a condition.

This is known as truthy and falsy values

  • Truthy → behaves like true
  • Falsy → behaves like false

Falsy Values:
Falsy values are values that are considered false in a boolean context.

List of Falsy Values:

false
0
""
null
undefined
NaN

Example of Falsy:

let value = 0;

if (value) {
  console.log("Truthy");
} else {
  console.log("Falsy");
}

O/P: Falsy

Enter fullscreen mode Exit fullscreen mode

Truthy Values

  • All values except falsy values are truthy.

Why It is Important:

*Reduces code length (no need for multiple conditions)
*Reduces unnecessary comparisons
*Useful for checking if a value exists
*Widely used in real-time applications (forms, APIs, login)

Top comments (0)