JavaScript if…else Statements
-
Conditional Execution:
if...elsestatements are used to conditionally execute blocks of code based on whether a specified condition is true or false. -
Syntax:
JavaScriptif (condition) { // Code to be executed if the condition is true } else { // Code to be executed if the condition is false } -
Example:
Code snippetconst age = 25; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are a minor."); } -
else if: You can chain multiple conditions usingelse ifstatements:JavaScriptconst grade = 85; if (grade >= 90) { console.log("Excellent!"); } else if (grade >= 80) { console.log("Great job!"); } else if (grade >= 70) { console.log("Good work!"); } else { console.log("Needs improvement."); } -
Logical Operators: Often used within conditions:
&&(AND): Both conditions must be true.||(OR): At least one condition must be true.!(NOT): Reverses the truth value of a condition.
JavaScriptif (age >= 18 && age <= 65) { // Code for adults between 18 and 65 } -
Ternary Operator: A shorthand for simple
if...elsestatements:JavaScriptconst isAdult = (age >= 18) ? true : false;
if...else statements are crucial for controlling the flow of your JavaScript programs, allowing you to make decisions and execute different code blocks based on specific conditions.