Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟨 Days 1–7 – JavaScript Fundamentals  ·  Day 03

Day 3: Operators, Conditions & Decisions

⏱ 85 min📶 Beginner🎯 100% self-study
Day 3 / 30

✅ Today you will learn

  • Arithmetic and assignment operators (%, **, +=)
  • Comparison: === vs == and why it matters
  • Logical operators &&, ||, ! and truthy/falsy values
  • if / else if / else, switch and the ternary operator
  • Modern helpers: ?? and ?.

🏢 In the real world

Business rules are conditions: “free delivery above ₹1,500”, “10% off for orders over 5 kg”, “shop closed on Monday”, “show Out of stock when quantity is 0”. Every app you will ever build is full of these decisions. Getting one comparison wrong can give away free sweets – or block real customers.

Arithmetic and assignment

JavaScript
const kg = 7, pricePerKg = 500;
console.log('Total:', kg * pricePerKg);
console.log('Boxes of 2 kg:', Math.floor(kg / 2), 'remaining kg:', kg % 2);   // % = remainder
console.log('Square:', 3 ** 2);                                               // power

let points = 100;
points += 50;    // points = points + 50
points -= 20;
points *= 2;
points++;        // +1
console.log('Loyalty points:', points);
Total: 3500 Boxes of 2 kg: 3 remaining kg: 1 Square: 9 Loyalty points: 261

Comparison: always use ===

JavaScript
console.log(5 === 5, 5 === '5');   // strict: value AND type
console.log(5 == '5', 0 == '');     // loose: converts types first – surprises!
console.log(null == undefined, null === undefined);
console.log(1500 >= 1500, 'apple' < 'banana', 5 !== '5');
true false true true true false true true true
⚠️ The == trap

0 == "" and "1" == 1 are true because == converts types. A coupon check like if (code == 0) can accept an empty string. Use === and !== everywhere; convert input with Number() first.

Logical operators and truthy / falsy

JavaScript
const total = 1800, isMember = false, city = 'Jaipur';

console.log(total >= 1500 && city === 'Jaipur');   // AND – both must be true
console.log(isMember || total > 2000);             // OR – at least one
console.log(!isMember);                            // NOT

// Falsy values: false, 0, '', null, undefined, NaN – everything else is truthy
const note = '';
console.log(note || 'No message');                 // fallback for empty values
const qty = 0;
console.log(qty || 1, qty ?? 1);                   // ?? only replaces null/undefined
true false true No message 1 0
OperatorMeaningUse when
&&Both trueAll rules must pass (age ≥ 18 && has ID)
||At least one true / first truthy valueAny rule passes, or a default for empty text
!Oppositeif (!isLoggedIn)
??First value that is not null/undefinedDefaults where 0 or "" are valid values
?.Stop if null/undefineduser?.address?.city – no crash when data is missing

if, else if, else

JavaScript
function deliveryCharge(total, distanceKm) {
  if (total >= 1500) {
    return 0;                       // free delivery
  } else if (distanceKm <= 5) {
    return 40;
  } else if (distanceKm <= 15) {
    return 80;
  } else {
    return -1;                      // we do not deliver that far
  }
}
console.log(deliveryCharge(1800, 20));
console.log(deliveryCharge(600, 3));
console.log(deliveryCharge(600, 12));
console.log(deliveryCharge(600, 30));
0 40 80 -1
💡 Order matters

Conditions are checked top to bottom and the first true one wins. Put the most specific or most important rule first – here “free above ₹1,500” beats every distance rule.

switch and the ternary operator

JavaScript
const day = 'Mon';
switch (day) {
  case 'Sat':
  case 'Sun':
    console.log('Weekend: open 8 am – 11 pm');
    break;
  case 'Mon':
    console.log('Closed for cleaning 🧹');
    break;
  default:
    console.log('Open 8 am – 10 pm');
}

const stock = 0;
const label = stock > 0 ? 'In stock' : 'Out of stock';   // condition ? yes : no
console.log(label);

const user = { name: 'Aarti' };
console.log(user.address?.city ?? 'City not added');
Closed for cleaning 🧹 Out of stock City not added

Real task: grade and discount calculator

HTML + JavaScript
<label>Order total ₹ <input id="t" type="number" value="2400"></label>
<label><input id="m" type="checkbox"> Member</label>
<button id="go">Check offer</button>
<p id="out"></p>

<script>
document.querySelector('#go').addEventListener('click', function () {
  const total = Number(document.querySelector('#t').value);
  const member = document.querySelector('#m').checked;
  let discount = 0;
  if (total >= 5000) discount = 0.15;
  else if (total >= 2000) discount = 0.10;
  else if (member) discount = 0.05;
  const pay = total - total * discount;
  const delivery = pay >= 1500 ? 0 : 60;
  document.querySelector('#out').textContent =
    `Discount ${discount * 100}% → pay ₹${pay + delivery} (delivery ₹${delivery})`;
});
</script>
▶  Try 900, 2400 and 6000, with and without Member

🏅 Job skills unlocked today

✔ Use arithmetic and assignment operators✔ Compare safely with === and !==✔ Combine rules with &&, ||, !, ?? and ?.✔ Write if/else, switch and ternary decisions

Practice tasks

🏋️ Practice – do it yourself

Task 1: Write a function grade(marks) that returns A+ (≥ 90), A (≥ 75), B (≥ 60), C (≥ 33) or Fail. Test it with 95, 76, 61, 40, 20.
Show solution
JavaScript
function grade(marks) {
  if (marks >= 90) return 'A+';
  if (marks >= 75) return 'A';
  if (marks >= 60) return 'B';
  if (marks >= 33) return 'C';
  return 'Fail';
}
for (const m of [95, 76, 61, 40, 20]) console.log(m, grade(m));
95 A+ 76 A 61 B 40 C 20 Fail
Task 2: A year is a leap year if divisible by 4, except centuries, unless divisible by 400. Write isLeap(year) with && and ||.
Show solution
JavaScript
function isLeap(y) {
  return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
}
console.log(2024, isLeap(2024), 1900, isLeap(1900), 2000, isLeap(2000), 2026, isLeap(2026));
2024 true 1900 false 2000 true 2026 false
Task 3: Use switch to print the shop timing for any weekday name.

Quick quiz

🧠 Quick Quiz – test yourself

1. 5 === '5' is…
Different types.
2. 17 % 5 equals…
Remainder.
3. Which value is truthy?
A non-empty string.
4. 0 ?? 10 gives…
?? keeps 0.
5. Without break, a switch case…
Fall-through.

Interview corner

💼 Interview Corner

== vs ===?

=== compares value and type without conversion; == converts types first (abstract equality), producing surprises such as 0 == "" being true. Prefer === except for the deliberate x == null check that matches both null and undefined.

What is the difference between || and ???

|| returns the right side for any falsy left value (0, "", false, NaN, null, undefined); ?? only for null or undefined. Use ?? when 0 or an empty string are valid values.

Summary

  • % gives remainders, ** powers, += shortens updates.
  • Always === / !==.
  • Falsy: false, 0, "", null, undefined, NaN; ?? and ?. handle missing data.
  • if/else for ranges, switch for fixed values, ternary for two outcomes.
➡️ Next

Day 4: loops – repeat work automatically: multiplication tables, bills for many items and attendance reports.

Frequently Asked Questions

When should I use switch instead of if?
When you compare one value against many fixed options (days, status codes, menu choices). For ranges (marks ≥ 90) use if/else.
Can I nest ternary operators?
You can, but it quickly becomes unreadable. Use if/else for more than two outcomes.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 4: Loops: for, while, for…of Your progress: 3 / 30 (10%) · Lesson 4 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free