Skip to Content
Course content

11: Operators and Expressions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Up until now, we've been mostly declaring variables and moving data around. But the real work of a program happens when you actually do something with that data. That's where operators and expressions come in. An expression is essentially any snippet of code that resolves to a value, and operators are the symbols we use to manipulate those values. It sounds simple, but this is where a lot of "JavaScript weirdness" creeps in if you aren't careful.

The danger of "close enough" comparisons

When you first start comparing values, it's tempting to use the loose equality operator ==. I've seen plenty of junior devs do this because it feels more flexible. For example, if you're checking a user's input from a form—which always comes in as a string—"10" == 10 returns true. JavaScript is trying to be "helpful" by converting the types for you behind the scenes.

// The naive way
let userAge = "21";
if (userAge == 21) { 
    console.log("Access granted"); 
}

The problem is that this "helpfulness" is a liability. JavaScript's type coercion rules are famously inconsistent. You'll eventually hit a case where [] == false is true, or null == undefined is true, and you'll spend three hours debugging a ghost in the machine. In a professional codebase, we almost never use ==. Instead, we use the strict equality operator ===. This checks both the value and the type. If you need the types to match, you should convert them explicitly so your intent is clear to anyone reading your code.

// The professional way
let userAge = "21";
if (Number(userAge) === 21) { 
    console.log("Access granted"); 
}

Cleaning up logic noise

I often see people writing long, multi-line if/else blocks to handle simple assignments. While it's not technically "wrong," it creates a lot of visual noise. If you're just deciding between two values based on a condition, the ternary operator ? : is your best friend. It allows you to express a conditional as a single expression rather than a control structure.

Think about a scenario where you're calculating a shipping fee. The naive approach looks like this:

let shippingCost;
if (isMember) {
    shippingCost = 0;
} else {
    shippingCost = 10;
}

That's five lines of code to do one simple thing. By using a ternary, we can condense this into a single, readable line. It's not just about saving space; it's about reducing the cognitive load for the next person reading your code.

const shippingCost = isMember ? 0 : 10;

Similarly, when you're dealing with "fallback" values—like providing a default username if the user didn't enter one—you can use the logical OR operator ||. Instead of checking if a variable is falsy with an if statement, you can just do const name = inputName || "Guest";. It's a shorthand that expresses "give me the first thing that is truthy."

Avoiding the repetition tax

Finally, let's talk about how you update values. When you're building a counter or totaling a price, you'll often see code like total = total + tax;. This is a bit redundant—you're mentioning the variable total twice in one line. JavaScript provides compound assignment operators to prune this away.

Using total += tax does the exact same thing, but it's the standard in the industry. The same goes for -=, *=, and /=. It seems like a tiny detail, but when you're staring at a 500-line file, these small reductions in redundancy make the logic much easier to scan. I've found that once you get used to these, the long-form version actually starts to feel like a typo.




📋 Practical Task

The Dynamic Shopping Cart Tax Calculator

You are building a checkout system for an e-commerce store. You need to calculate the final price of an item based on three factors: the base price, whether the user has a discount coupon, and the local tax rate.

Your goals:

  • Create a variable basePrice (e.g., 100) and a boolean hasCoupon.
  • Use a ternary operator to determine a discountAmount: if hasCoupon is true, the discount is 20; otherwise, it's 0.
  • Calculate the subtotal by subtracting the discount from the base price.
  • Use a compound assignment operator to add a 7% tax (0.07 * subtotal) to the subtotal to get the finalPrice.
  • Use a strict equality operator to check if the finalPrice is exactly equal to a specific target value (e.g., 87.36) and log the result to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.