JavaScript Conditions
Conditions program ko decision lene deti hain. JavaScript kisi expression ko evaluate karke decide kar sakta hai ki kaunsa code run hoga aur kaunsa skip hoga.
What is a condition?
A condition is an expression used to make a decision. JavaScript evaluates the expression in a boolean context and then chooses which block of code to execute.
const score = 75;
if (score >= 40) {
console.log("Pass");
}Condition ko question samjho: “Kya score 40 ya usse zyada hai?” Agar answer true hai to block run hota hai. Agar false hai to block skip ho jata hai.
The if statement
if runs a block only when its condition is truthy.
const isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back");
}Parentheses contain the condition and curly braces contain the code block.
if...else
Use else when you need an alternative path if the if condition is false.
const age = 16;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}else if chains
Use else if when multiple mutually exclusive conditions need to be checked in order.
const score = 82;
if (score >= 90) {
console.log("Grade A+");
} else if (score >= 75) {
console.log("Grade A");
} else if (score >= 60) {
console.log("Grade B");
} else if (score >= 40) {
console.log("Pass");
} else {
console.log("Try again");
}Conditions with comparison operators
Comparison operators from Chapter 4 are commonly used inside conditions.
const temperature = 31;
if (temperature > 30) {
console.log("Hot day");
}
if (temperature === 31) {
console.log("Exactly 31 degrees");
}Prefer strict equality === when comparing values unless coercion is explicitly intended.
Combining conditions
Logical operators let you combine multiple checks.
const isLoggedIn = true;
const hasSubscription = true;
if (isLoggedIn && hasSubscription) {
console.log("Open course");
}
const role = "editor";
if (role === "admin" || role === "editor") {
console.log("Editing allowed");
}&&requires both sides to be truthy.||needs at least one truthy side.!reverses truthiness.
Checking numeric ranges
JavaScript does not support mathematical chained comparisons such as 18 <= age <= 60. Write each comparison explicitly.
const age = 25;
if (age >= 18 && age <= 60) {
console.log("Within range");
}18 <= age <= 60 does not mean what it means in mathematics. Use && between separate comparisons.Truthy and falsy in conditions
An if condition does not require a literal boolean. JavaScript converts the tested value to boolean truthiness.
const userName = "Broun";
if (userName) {
console.log("Name is available");
}
const message = "";
if (!message) {
console.log("Message is empty");
}Common falsy values include false, 0, empty string, null, undefined and NaN.
Explicit checks can be clearer
Truthy checks are concise, but explicit comparisons can communicate intent better when values such as 0 or an empty string are valid data.
const cartCount = 0;
if (cartCount === 0) {
console.log("Cart is empty");
}Nested conditions
An if block can contain another condition, but too much nesting makes code harder to read.
const isLoggedIn = true;
const role = "student";
if (isLoggedIn) {
if (role === "student") {
console.log("Open student dashboard");
}
}Nested if valid hai, lekin 4–5 levels deep nesting ko avoid karo. Conditions ko simple aur readable rakhna debugging ko easy banata hai.
The switch statement
switch is useful when one value is compared against several exact cases.
const day = "monday";
switch (day) {
case "monday":
console.log("Start the week");
break;
case "friday":
console.log("Almost weekend");
break;
default:
console.log("Regular day");
}switch matching uses strict comparison behavior. The default branch runs when no case matches.
Why break matters in switch
Without break, execution can continue into following cases. This is called fall-through.
const level = 1;
switch (level) {
case 1:
console.log("Beginner");
break;
case 2:
console.log("Intermediate");
break;
default:
console.log("Unknown level");
}break unless they deliberately want multiple cases to share behavior.Grouping switch cases
Multiple cases can intentionally share the same block.
const role = "editor";
switch (role) {
case "admin":
case "editor":
console.log("Can edit content");
break;
default:
console.log("Read only");
}Ternary operator
The conditional or ternary operator is a compact expression for choosing between two values.
const score = 75;
const result = score >= 40 ? "Pass" : "Fail";
console.log(result);Syntax: condition ? valueIfTrue : valueIfFalse.
if...else.if...else vs switch vs ternary
- Use
if...elsefor ranges, multiple expressions and flexible conditions. - Use
switchwhen one value is matched against several exact cases. - Use ternary for a short two-way value choice.
Practical access check
const isLoggedIn = true;
const progress = 80;
if (!isLoggedIn) {
console.log("Please sign in");
} else if (progress === 100) {
console.log("Course complete");
} else if (progress >= 75) {
console.log("Almost complete");
} else {
console.log("Keep learning");
}Beginner best practices
- Conditions ko short and readable rakho.
- Equality ke liye generally
===and!==prefer karo. - Complex boolean logic me parentheses use karo when it improves clarity.
- Range checks ko separate comparisons with
&&me likho. switchme accidental fall-through avoid karo.- Nested ternaries avoid karo.
- Real values such as
0ko falsy shortcut se accidentally reject mat karo.
Common beginner mistakes
=ko condition me equality operator samajhna.==aur===difference ignore karna.else ifconditions wrong order me rakhna.18 <= age <= 60jaisi mathematical chaining likhna.switchcases mebreakbhoolna.- Boolean logic ko unnecessarily deeply nest karna.
- Complex nested ternary expressions banana.
- Truthy/falsy behavior samjhe bina shortcuts use karna.
Chapter checklist
if,elseandelse ifuse kar sakte ho?- Logical operators ke saath conditions combine kar sakte ho?
- Truthy/falsy values condition me kaise behave karti hain clear hai?
- Numeric range correctly check kar sakte ho?
switch,case,breakanddefaultsamajh aaye?- Ternary operator kab appropriate hai clear hai?
Practice Task — Decision Lab
Browser Console me conditions ki practice karo.
agevariable banao aur 18+ ke liye adult/minor message print karo.scorese pass/fail condition banao.- Score ranges ke liye 4-level
else ifgrade system banao. isLoggedInaurhasSubscriptionko&&ke saath combine karo.- Role
adminyaeditorho to access allow karo using||. - Age 18 se 60 ke range me hai ya nahi correctly check karo.
- Empty string aur non-empty string ko
ifme test karo. - Weekday name ke liye
switchstatement banao withdefault. - Ternary se
score >= 40ka result"Pass"ya"Fail"assign karo. - Intentionally ek
switchcase sebreakremove karke fall-through observe karo; phir fix karo.