Conditional Statements | If, Switch & Ternary Operator | JavaScript Journey | In Hindi | Death Code - DeathCode

JavaScript Conditional Statements and Operators

Understanding Conditional Statements

Conditional statements in JavaScript allow you to execute different blocks of code based on certain conditions. The most common conditional statements are if, else if, and else.

Example 1: Age Check

// let age = 17
 
if(age > 28){
   console.log("Age is greater than 28");
}else if (age >= 18) {
   console.log("You are now Adult");
}else{
   console.log("You are now Minor");
}   

This code checks the value of age. If age is greater than 28, it logs that the age is greater than 28. If the age is between 18 and 28, it logs that the user is an adult. Otherwise, it logs that the user is a minor.

Example 2: User Login Status

let isLogin = true;
 
if(isLogin){
   console.log("user is logged in");
}else{
   console.log("user is not logged in");
}

This code checks if the user is logged in. If isLogin is true, it logs that the user is logged in; otherwise, it logs that the user is not logged in.

Example 3: Ternary Operator

isLogin = false;
 
isLogin ? console.log("user is logged in") : console.log("user is not logged in");

The ternary operator is a shorthand for if-else statements. It checks the condition and executes the first expression if true, or the second expression if false.

Example 4: Switch Statement

let week = "fri";
 
switch(week){
   case "mon":
       console.log("Monday");
       break;
   case "tue":
       console.log("Tuesday");
       break;
   case "wed":
       console.log("Wednesday");
       break;
   case "fri":
       console.log("Friday");
       break;
   default:
       console.log("Invalid day");
}

The switch statement evaluates the value of week and executes the corresponding case. If none match, it defaults to "Invalid day".

Understanding Falsy and Truthy Values

In JavaScript, certain values are considered falsy (e.g., false, 0, null, "") and others are truthy (e.g., true, non-zero numbers, non-empty strings). This affects how conditions are evaluated.

Β© 2024 DeathCode. All Rights Reserved.