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

Imagine you're talking to a very eager, but slightly presumptuous, personal assistant. If you tell them, "I have two apples and one orange," they don't try to mathematically add those together to get "three fruit-things." They realize you're just listing items, so they keep them as a list. But if you say, "I have two apples and I just bought three more," your assistant immediately does the math and tells you that you have five apples.

JavaScript does the exact same thing. This is Type Coercion. It's the language's attempt to be "helpful" by automatically converting a value from one type to another so that an operation doesn't just crash your entire program. The problem is that JavaScript's logic for these guesses can feel... erratic.

The Double Life of the Plus Sign

The + operator is the most frequent source of headaches because it has two completely different jobs: addition and concatenation (gluing strings together). When JavaScript sees a +, it checks the types. If either side is a string, it decides, "Oh, we're just making a list!" and converts everything to a string.

let price = 10;
let tax = '2'; 

console.log(price + tax); // Result: "102"

I can't tell you how many times I've seen a junior dev spend an hour wondering why their shopping cart total was "10020" instead of 120. It happens because the value coming from an HTML input field is always a string, even if the user typed a number. JavaScript sees that string and decides to glue the numbers together instead of adding them.

When Math Operators Force the Issue

Unlike the plus sign, operators like -, *, and / only have one job: math. They don't know how to "concatenate" a subtraction. So, if you try to subtract a number from a string, JavaScript will aggressively try to convert that string into a number first.

let score = '100';
console.log(score - 10); // Result: 90

In this case, JavaScript thinks, "You can't subtract 10 from a word, so '100' must actually be a number." It works—until it doesn't. If the string contains something that isn't a number (like '100px'), JavaScript gives up and returns NaN (Not a Number), which is the language's way of throwing its hands up in the air.

Truthiness and the Boolean Shortcut

You'll often see coercion inside if statements. You don't always have to explicitly check if (userEmail === ""). JavaScript coerces whatever is inside the parentheses into a boolean (true or false).

Most things are "truthy," but there is a short list of "falsy" values that always coerce to false: false, 0, "" (empty string), null, undefined, and NaN.

let username = "";

if (!username) {
  console.log("Please enter a name!"); // This runs because "" is falsy
}

I personally love this shorthand, but be careful. If 0 is a valid input for your app (like a zero-dollar balance), if (!balance) will trigger even if the balance is actually zero, because zero is falsy. Always ask yourself if 0 or "" should actually count as "false" in your specific logic.




📋 Practical Task

Fixing the Broken Invoice Totalizer

You are debugging a small billing module. The current code is taking a base price (number) and adding a shipping fee (which is coming from a form as a string). Instead of calculating the total, it's concatenating them.

Your Task: Modify the calculateTotal function so that it performs actual addition instead of string concatenation. You must ensure the shipping fee is treated as a number before adding it.

function calculateTotal(basePrice, shippingFee) {
  // BUG: If basePrice is 100 and shippingFee is '15', 
  // this currently returns "10015"
  return basePrice + shippingFee;
}

const price = 100;
const shipping = '15';

console.log("Total Invoice: $" + calculateTotal(price, shipping)); 
// Expected Output: Total Invoice: $115
Rating
0 0

There are no comments for now.

to be the first to leave a comment.