1. Purpose of Logic Statements
Logic statements allow a program to choose between different execution paths based on conditions.
Concept Overview
- A condition evaluates to true or false.
- A branch executes only when its condition is satisfied.
- Logic statements implement control flow.
[Condition?]
|
True False
| |
if block else block
2. if and if...else
Basic if
let temperature = 30;
if (temperature > 25){
console.log("It is warm outside.");
}
if...else
let isLoggedIn = false;
if(isLoggedIn){
console.log("Welcome back!");
}else{
console.log("Please log in first.");
}
3. else if Chain
let score=78;
if(score>=90){
console.log("Grade A");
}else if(score>=80){
console.log("Grade B");
}else if(score>=70){
console.log("Grade C");
}else{
console.log("Grade D");
}
Conditions are checked from top to bottom. The first true condition executes.
4. Truthy and Falsy
Falsy values:
- false
- 0
- -0
- ""
- null
- undefined
- NaN
let name="";
if(name){
console.log("Name is provided");
}else{
console.log("Name is missing");
}
5. Comparison and Logical Operators
| Operator | Meaning |
|---|---|
| == | Equal (coercion) |
| === | Strict Equal |
| != | Not Equal |
| !== | Strict Not Equal |
| > | Greater Than |
| < | Less Than |
| >= | Greater Than or Equal |
| <= | Less Than or Equal |
Logical Operators
- && AND
- || OR
- ! NOT
let age=20;
let hasID=true;
if(age>=18 && hasID){
console.log("Access granted");
}
let isAdmin=false;
let isModerator=true;
if(isAdmin || isModerator){
console.log("You can manage comments.");
}
let isComplete=false;
if(!isComplete){
console.log("Task is not complete yet.");
}
6. Conditional (Ternary) Operator
let age=17;
let message=(age>=18)?"Adult":"Minor";
console.log(message);
Ternary is a concise alternative to simple if...else statements.
7. switch Statement
let day="Wednesday";
switch(day){
case "Monday":
console.log("Start of week");
break;
case "Wednesday":
console.log("Middle of week");
break;
default:
console.log("Another day");
}
Without break, execution falls through to the next case.
8. Choosing Between if and switch
Use if...else for ranges and inequalities. Use switch for matching a single variable against multiple values.
9. Complete Example - Movie Ticket Price Calculator
let age=16;
let isStudent=true;
let dayOfWeek="Wednesday";
let basePrice;
if(age<12){
basePrice=5;
}else if(age<18){
basePrice=8;
}else{
basePrice=10;
}
let discount=isStudent?2:0;
let finalPrice;
switch(dayOfWeek){
case "Wednesday":
finalPrice=basePrice-discount-1;
break;
default:
finalPrice=basePrice-discount;
}
console.log(finalPrice);
Summary
- if
- if...else
- else if
- Truthy & Falsy
- Comparison Operators
- Logical Operators
- Ternary Operator
- Switch Statement
- Fall-through
- Choosing between if and switch