Lesson 3: Basic Operators - Math and Comparisons

What You'll Learn

  • How to perform mathematical calculations
  • How to compare values
  • How to combine conditions with logical operators
  • The order in which operations are performed

Why This Matters

Operators are the symbols that tell your computer to perform operations - like + for addition or > for "greater than". They're essential for calculations, making decisions, and comparing values.

---

Part 1: Arithmetic Operators (Math)

Create a new file: lesson-03/operators.js

Basic Math Operations

const a = 10;
const b = 3;

// Addition
const sum = a + b;
console.log(`${a} + ${b} = ${sum}`);  // Output: 10 + 3 = 13

// Subtraction
const difference = a - b;
console.log(`${a} - ${b} = ${difference}`);  // Output: 10 - 3 = 7

// Multiplication
const product = a * b;
console.log(`${a} * ${b} = ${product}`);  // Output: 10 * 3 = 30

// Division
const quotient = a / b;
console.log(`${a} / ${b} = ${quotient}`);  // Output: 10 / 3 = 3.3333...

// Modulus (Remainder)
const remainder = a % b;
console.log(`${a} % ${b} = ${remainder}`);  // Output: 10 % 3 = 1

Understanding Each Operator

Operator Name What It Does Example Result
+ Addition Adds two numbers 5 + 3 8
- Subtraction Subtracts second from first 5 - 3 2
* Multiplication Multiplies two numbers 5 * 3 15
/ Division Divides first by second 6 / 3 2
% Modulus Gets the remainder 7 % 3 1

What is Modulus (%)?

The modulus operator gives you the remainder after division:

console.log(10 % 3);  // 10 ÷ 3 = 3 remainder 1, so output: 1
console.log(15 % 4);  // 15 ÷ 4 = 3 remainder 3, so output: 3
console.log(20 % 5);  // 20 ÷ 5 = 4 remainder 0, so output: 0
When is this useful?
  • Checking if a number is even: n % 2 === 0
  • Cycling through values (like days of the week)
  • Determining positions in a repeating pattern

---

Part 2: String Concatenation

The + operator also works with strings:

const firstName = "John";
const lastName = "Doe";

const fullName = firstName + " " + lastName;
console.log(fullName);  // Output: John Doe

// You can mix strings and numbers (they get converted to strings)
const age = 30;
const message = "I am " + age + " years old";
console.log(message);  // Output: I am 30 years old
Better way: Use template literals (remember from Lesson 2):
const age = 30;
const message = `I am ${age} years old`;
console.log(message);  // Output: I am 30 years old

---

Part 3: Comparison Operators

Comparison operators compare two values and return a boolean (true or false).

const x = 10;
const y = 5;

// Equal to
console.log(x === y);  // false (10 is not equal to 5)

// Not equal to
console.log(x !== y);  // true (10 is not equal to 5)

// Greater than
console.log(x > y);    // true (10 is greater than 5)

// Less than
console.log(x < y);    // false (10 is not less than 5)

// Greater than or equal to
console.log(x >= y);   // true (10 is greater than or equal to 5)

// Less than or equal to
console.log(x <= y);   // false (10 is not less than or equal to 5)

Comparison Operators Table

Operator Name What It Checks Example Result
=== Equal Are values the same? 5 === 5 true
!== Not equal Are values different? 5 !== 3 true
> Greater than Is left bigger? 5 > 3 true
< Less than Is left smaller? 5 < 3 false
>= Greater or equal Is left bigger or same? 5 >= 5 true
<= Less or equal Is left smaller or same? 5 <= 3 false

Important: === vs == (JavaScript Best Practice)

// Always use === (strict equality)
console.log(5 === 5);      // true
console.log(5 === "5");    // false (different types!)

// Avoid == (loose equality - can cause bugs)
console.log(5 == "5");     // true (converts types - confusing!)
Rule: Always use === and !== in JavaScript. They check both value AND type.

---

Part 4: Logical Operators

Logical operators let you combine multiple conditions.

AND Operator (&&)

Both conditions must be true:

const age = 25;
const hasLicense = true;

// Can they drive? Need to be 18+ AND have license
const canDrive = age >= 18 && hasLicense;
console.log(canDrive);  // true (both conditions are true)

// Example with false result
const age2 = 16;
const canDrive2 = age2 >= 18 && hasLicense;
console.log(canDrive2);  // false (age condition is false)
Truth table for AND:
  • true && true = true
  • true && false = false
  • false && true = false
  • false && false = false

OR Operator (||)

At least one condition must be true:

const isWeekend = false;
const isHoliday = true;

// Can they sleep in? Weekend OR holiday
const canSleepIn = isWeekend || isHoliday;
console.log(canSleepIn);  // true (one condition is true)

// Example with false result
const isWeekend2 = false;
const isHoliday2 = false;
const canSleepIn2 = isWeekend2 || isHoliday2;
console.log(canSleepIn2);  // false (both are false)
Truth table for OR:
  • true || true = true
  • true || false = true
  • false || true = true
  • false || false = false

NOT Operator (!)

Flips true to false and false to true:

const isRaining = false;
const isSunny = !isRaining;
console.log(isSunny);  // true (NOT false = true)

const isLoggedIn = true;
const isLoggedOut = !isLoggedIn;
console.log(isLoggedOut);  // false (NOT true = false)

Combining Logical Operators

const age = 20;
const hasTicket = true;
const hasID = true;

// Can enter concert? Must be 18+ AND (have ticket OR have ID)
const canEnter = age >= 18 && (hasTicket || hasID);
console.log(canEnter);  // true
Note the parentheses: They control which operations happen first (like in math).

---

Part 5: Assignment Operators

Shortcuts for updating variables:

let score = 10;

// Regular way
score = score + 5;
console.log(score);  // 15

// Shortcut way
score += 5;  // Same as: score = score + 5
console.log(score);  // 20

// Other shortcuts
score -= 3;  // Subtract 3 (same as: score = score - 3)
console.log(score);  // 17

score = 2;  // Multiply by 2 (same as: score = score  2)
console.log(score);  // 34

score /= 2;  // Divide by 2 (same as: score = score / 2)
console.log(score);  // 17

Increment and Decrement

Special shortcuts for adding/subtracting 1:

let counter = 0;

counter++;  // Increment (add 1) - same as: counter = counter + 1
console.log(counter);  // 1

counter++;
console.log(counter);  // 2

counter--;  // Decrement (subtract 1) - same as: counter = counter - 1
console.log(counter);  // 1

---

Part 6: Order of Operations

Like in math, operators have an order (precedence):

const result1 = 2 + 3 * 4;
console.log(result1);  // 14 (not 20! Multiplication happens first)

const result2 = (2 + 3) * 4;
console.log(result2);  // 20 (parentheses force addition first)
Order (highest to lowest):
  1. () - Parentheses
  2. *, /, % - Multiplication, Division, Modulus
  3. +, - - Addition, Subtraction
  4. >, <, >=, <= - Comparisons
  5. ===, !== - Equality
  6. && - Logical AND
  7. || - Logical OR
Pro tip: When in doubt, use parentheses to make your intention clear!

---

Practice Exercises

Exercise 1: Calculate Area

Create a program that calculates the area of a rectangle:

const width = 10;
const height = 5;
// Calculate and print the area

Exercise 2: Temperature Converter

Convert Celsius to Fahrenheit using: F = C * 9/5 + 32
const celsius = 25;

// Calculate and print Fahrenheit

Exercise 3: Even or Odd

Use the modulus operator to check if a number is even:

const number = 7;
const isEven = number % 2 === 0;
console.log(`${number} is even: ${isEven}`);

Exercise 4: Age Verification

Check if someone can vote (age >= 18) and is registered:

const age = 20;
const isRegistered = true;
const canVote = // your code here
console.log(`Can vote: ${canVote}`);

Exercise 5: Shopping Discount

A store gives a discount if you buy 5+ items OR spend $50+:

const itemCount = 3;
const totalSpent = 60;
const getsDiscount = // your code here
console.log(`Gets discount: ${getsDiscount}`);

---

Common Mistakes

Mistake 1: Using = Instead of ===

const x = 5;
if (x = 10) {  // ❌ WRONG! This assigns 10 to x
  console.log("Equal");
}
Fix:
if (x === 10) {  // ✅ CORRECT! This compares
  console.log("Equal");
}

Mistake 2: Confusing && and ||

// Wants: age is 18 OR older

const canVote = age >= 18 && age >= 18;  // ❌ Wrong operator
Fix:
const result = 7 / 2;

console.log(result);  // 3.5 (not 3! JavaScript keeps decimals)

If you want an integer, use Math.floor():

const result = Math.floor(7 / 2);

console.log(result);  // 3

---

Key Concepts Summary

Category Operators Purpose
Arithmetic +, -, *, /, % Math calculations
Comparison ===, !==, >, <, >=, <= Compare values
Logical &&, ||, ! Combine conditions
Assignment =, +=, -=, *=, /= Store/update values
Increment/Decrement ++, -- Add/subtract 1

What You Learned

  • ✅ How to perform math operations (+, -, *, /, %)
  • ✅ How to compare values (===, !==, >, <, >=, <=)
  • ✅ How to combine conditions with && and ||
  • ✅ How to use assignment shortcuts (+=, -=, ++, --)
  • ✅ The order in which operations are performed
  • ✅ Always use === instead of == in JavaScript

What's Next?

In the next lesson, you'll learn about conditional statements (if/else) - how to make your program make decisions based on conditions!