Conditional Statements in JavaScript
Conditional Statements Conditional statements allow JavaScript to execute different blocks of code based on whether a condition is true or false. if - The if statement executes a block of code only if the condition is true. if...else - Use if...else when you want one block of code to run if the condition is true and another block if it's false. if...else if...else - Use this when you have multiple conditions to check. switch statement - The switch statement is used when you have many possible values for one variable. Nested if statement - You can also write an if statement inside another if. Ternary Operator - An optimized one-line shorthand for standard if...else blocks ** If Statement ** let age = 20 ; if ( age >= 18 ) { console . log ( " Eligible to vote " ); } //Output: Eligible to vote ** if else Statement ** let age = 16 ; if ( age >= 18 ) { console . log ( " Eligible to vote " ); } else { console . log ( " Not eligible to vote " ); } // Output: Not eligible to vote ** if ... else if ... else ** let marks = 85 ; if ( marks >= 90 ) { console . log ( " Grade A " ); } else if ( marks >= 75 ) { console . log ( " Grade B " ); } else if ( marks >= 50 ) { console . log ( " Grade C " ); } else { console . log ( " Fail " ); } // Output: Grade B ** switch statement ** let day = 3 ; switch ( day ) { case 1 : console . log ( " Monday " ); break ; case 2 : console . log ( " Tuesday " ); break ; case 3 : console . log ( " Wednesday " ); break ; default : console . log ( " Invalid Day " ); } // Output: Wednesday // Important: The break statement stops the execution after the matching case.We must compulsory to use break statement because if you don't use break, JavaScript will continue executing the next cases even the output is correct. ** Nested if Statement ** let age = 20 ; let hasLicense = true ; if ( age >= 18 ) { if ( hasLicense ) { console . log ( " You can drive. " ); } } // Output: You can drive. ** Ternary Operator ** let isLoggedIn = true ; let systemMessage = is