Conditional Statements in JavaScript
JAVASCRIPT CONDITIONAL STATEMENTS JavaScript conditional statements are used to make decisions in a program based on given conditions. They control the flow of execution by running different code blocks depending on whether a condition is true or false. Conditions are evaluated using comparison and logical operators. They help in building dynamic and interactive applications by responding to different inputs. Types of Conditional Statements 1. if Statement The if statement checks a condition written inside parentheses. If the condition evaluates to true, the code inside {} is executed; otherwise, it is skipped. Executes code only when a specified condition is true. Useful for making simple decisions in a program. Syntax : if ( condition ) { // code runs if condition is true } let x = 20 ; if ( x % 2 === 0 ) { console . log ( " Even " ); } if ( x % 2 !== 0 ) { console . log ( " Odd " ); }; Output Even 2. if-else Statement The if-else statement executes one block of code if a condition is true and another block if it is false. It ensures that exactly one of the two code blocks runs. Used when there are two possible outcomes. The else block runs when the if condition is not satisfied. let age = 25 ; if ( age >= 18 ) { console . log ( " Adult " ) } else { console . log ( " Not an Adult " ) }; Output Adult 3. else if Statement The else if statement is used to test multiple conditions in sequence. It executes the first block whose condition evaluates to true. Allows checking more than two conditions. Evaluated from top to bottom until a true condition is found. const x = 0 ; if ( x > 0 ) { console . log ( " Positive. " ); } else if ( x < 0 ) { console . log ( " Negative. " ); } else { console . log ( " Zero. " ); }; Output Zero . 4. Using Switch Statement (JavaScript Switch Case) The switch statement evaluates an expression and executes the matching case block based on its value. It provides a clean and readable way to handle multiple conditions for a single varia