Operators: The Math & Logic of JS

Operators: The Math & Logic of JS in JavaScript: Operators are the "Verbs" of programming. They allow you to add numbers, compare values, or make logical…

Concept Explanation

Operators are the "Verbs" of programming. They allow you to add numbers, compare values, or make logical decisions.

A special feature of JavaScript is the difference between == (Loose Equality) and === (Strict Equality).

  • == is like a parent who says "I guess a string '5' is the same as the number 5."
  • === is like a strict judge who says "No, they are totally different types!"

Syntax or Core Structure

Arithmetic and Comparison

let x = 10 + 5; // 15
let y = 10 % 3; // 1 (Remainder)

// THE MOST IMPORTANT RULE
console.log(5 == "5");  // true (Loose - converted the type)
console.log(5 === "5"); // false (Strict - strictly better!)

Logical Operators (AND, OR, NOT)

const hasKey = true;
const hasCode = false;

// AND (both must be true)
console.log(hasKey && hasCode); // false

// OR (at least one must be true)
console.log(hasKey || hasCode); // true

// NOT (flip the value)
console.log(!hasKey); // false

Common Mistakes

  1. Loose Equality: Using == leads to incredibly weird bugs like 0 == "" being true. Always use ===.
  2. Operator Precedence: Forgetting that * happens before +. Use parentheses: (5 + 5) * 2 to be sure.
  3. Bitwise over Logical: Beginners sometimes use & (one ampersand) instead of &&. These are "Bitwise" operators and behave very differently!

Best Practices

  • Strict Equality: Use === and !== 100% of the time.
  • Explicit is better than Implicit: Use parentheses to make your math clear, even if you know the order of operations.
  • Short-Circuiting: Use || to provide default values: const name = user.name || "Guest";

Practice Exercises

  1. The Equality Lab: Compare null, undefined, 0, and "" using both == and ===.
  2. The Calculator: Create a function that takes two numbers and an operator (+, -, *, /) and returns the result.
  3. The Logic Gate: Write a logical expression that returns true only if a user is "over 18" AND "has a valid ID."