if-else
if-else
Section titled “if-else”Introduction
Section titled “Introduction”The if statement executes a block of code if a condition is truthy. else if and else provide alternative branches.
Syntax
Section titled “Syntax”if (condition) { // runs if condition is truthy} else if (otherCondition) { // runs if first condition is falsy and otherCondition is truthy} else { // runs if all conditions are falsy}Visual Explanation
Section titled “Visual Explanation”flowchart TD Start["Start"] Cond{"age >= 18?"} Yes["You are an adult"] No["You are a minor"]
Start --> Cond Cond -->|Yes| Yes Cond -->|No| NoExamples
Section titled “Examples”const age = 20;
if (age >= 18) { console.log('You can vote');} else if (age >= 16) { console.log('You can drive');} else { console.log('Too young');}Truthiness in Conditions
Section titled “Truthiness in Conditions”if ('hello') { } // runs — truthyif (0) { } // doesn't run — falsyif (null) { } // doesn't run — falsyif ([]) { } // runs — truthy (empty array)if ({}) { } // runs — truthy (empty object)Best Practices
Section titled “Best Practices”- Always use
===for comparisons (not==) - Prefer
switchfor many conditions on the same value - Use guard clauses to avoid deep nesting