Why Understanding Javascript's Type System Early Will Save You Later

Sangy KSangy K
7 min read

Welcome to Javascript, where "5" + 5 becomes "55", and 0.1 + 0.2 somehow doesn't equal 0.3 🀯.

It's a wonderfully flexible languageβ€”but with that flexibility comes a whole lot of "*Wait, what just happened?*" moments.. One moment you're working with numbers, the next you're unexpectedly building strings, and null mysteriously reports itself as an object. πŸ˜…

Let's break this down clearly: how Javascript stores variables (by value or reference), changes their types dynamically, and sometimes coerces them into actions you didn't explicitly ask forβ€” but Javascript thought you wanted.

🧊 Understanding Variable Storage: Value vs Reference

In Javascript, how a variable is stored in memory depends on what kind of data it holds.

And that's importantβ€”because it changes how your values behave when you copy them, change them, or pass them around.

πŸ”Ή Primitives Are Stored by Value

Javascript's primitive types β€” string, number, boolean, null, undefined, symbol, and bigint β€” are stored by value.

What does that mean?

When you assign a primitive value to a variable, Javascript stores a copy of the actual value, not a link to the original.

let a = 10;
let b = a;
b = 20;
console.log(a); // Still 10

When you change b, it doesn't touch a. They're entirely separate values in memory β€” like photocopying a document. You can scribble all over your copy without changing the original.

Whenever you assign a primitive (here, a to b) to another variable, Javascript makes a fresh copy: no shared references, no surprises.

πŸ”Ή Objects & Arrays Are Stored by Reference

When you create an object or array in Javascript, the engine stores the actual data somewhere in memory (usually the heap, where large or dynamic data lives).

But the variable doesn't hold the object itself β€” it holds a reference (or pointer) to the location where that object is stored.

Think of it like a signpost πŸ“ pointing to the object's real home.

The variable knows where the object is, but it doesn't carry all the details itself.

πŸ”— What Happens When You Assign It?

When you assign an object to another variable, you're copying that signpost, not the object itself.

Both variables now point to the same memory location, so if you change the object through one variable, you'll see the change through the other.

let obj1 = { name: "Luna" };
let obj2 = obj1;

obj2.name = "Marco";

console.log(obj1.name); // "Marco"

Both obj1 and obj2 still point to the same place in memory, so when you update obj2.name, you also update what obj1 sees.

πŸ’€ Be careful when passing objects to functions, returning them, or sharing them across components. If one part of your code changes the object, the whole app sees the change.

βœ… Pro Tip:

If you need a fresh copy of the object (a new spot in memory), try:

  • structuredClone(obj) β†’ for a deep copy (copies everything inside).

  • Spread syntax { ...obj } β†’ for a shallow copy (copies only the top level).

let obj3 = structuredClone(obj1); // Now obj3 is completely independent

This way, your objects won't step on each other's toes.

πŸŒ€ Dynamic Typing in Javascript

Javascript doesn't ask you to declare what type your variable is. You just assign a value, and Javascript figures out the type at runtime.

And yes, that means a variable's type can change at any time β€” no declarations, no safety nets.

Example:

let data = 42; // number
data = "forty-two"; // now a string
data = true; // now a boolean!

This gives Javascript its flexibility and ease of use, but it also means you can run into weird bugs if you're not paying attention.

βœ… Quick Debug Tip:

Use typeof whenever you're unsure what type a variable holds.

console.log(typeof data); // "boolean"

⚠️ Common Gotcha:

let input = prompt("Enter your age:");
console.log(typeof input); // always "string"

Even if the user types a number, the prompt always returns a string.

That's where type conversion comes inβ€”turning one data type into another so your code behaves correctly.

πŸ”„ Type Conversion Vs Type Coercion

In Javascript, sometimes you change a data type on purpose (this is called conversion), and sometimes Javascript changes it for you, whether you like it or not (this is called coercion).

  • Conversion: You tell Javascript, "Please change this to a number." βœ…

  • Coercion: Javascript says, "Hey, I think you meant this to be a string..." whether you asked for it or not. πŸ™ƒ

πŸ”Ή Explicit Conversion (You Control It)

You can manually convert values using built-in functions.

Example from before:

let input = prompt("Enter your age:");
console.log(typeof input); // always "string"

let age = Number(input); // Now it's a number

Here, you're explicitly converting a string to a number using Number().

βœ… Other handy converters:

  • String(value) β†’ converts anything to a string.

  • Boolean(value) β†’ converts to true/false

  • parseInt(), parseFloat() β†’ convert strings to numbers (with more control)

πŸ”Έ Implicit Coercion (Javascript Makes a Guess)

This is where Javascript tries to be helpful... and sometimes causes confusion.

Examples:

"5" * 2 // 10 β€” JS turns "5" into a number
"5" + 2 // "52" β€” JS turns 2 into a string
true + 1 // 2 β€” JS turns true into 1

➑️ Javascript decides what to coerce based on the operator.

  • + prefers strings (if either side is a string, it does string concatenation).

  • *, /, and - prefer numbers and try to convert things to numbers.

⚠️ Real-World Scenario: HTML Input Values

HTML input fields always return strings, even if the user types a number:

<input id="qty" value="2">
let quantity = document.getElementById("qty").value; // "2"
let total = quantity * 5; // 10 β€” JS coerces "2" to 2
let total = quantity + 5; // "25" β€” uh oh, string concatenation!
let total = Number(quantity) + 5; // 7 β€” βœ… correct

So what's happening?

  • The *, /, and - operators force Javascript to treat "2" as a number.

  • But the + operator can either add numbers or concatenate strings, and Javascript picks string concatenation if one side is a string.

βœ… Best Practice:

Manually convert your data so Javascript doesn't have to guess.

It makes your code easier to read, and you avoid bugs caused by unexpected coercion.

βž• Working with Numbers

You'd think math would be simple, but not in Javascript.

Basic arithmetic works just fine:

let price = 10;
let tax = 0.2;

let total = price + (price * tax); // 12

Nothing wild there.

But the moment you start working with decimals, the decimal precision will haunt you πŸ‘».

Example:

console.log(0.1 + 0.2); // 0.30000000000000004 😬

This isn't a Javascript bug β€” it's how floating-point numbers work in binary.

The computer can't represent some decimal fractions exactly, such as 0.1 or 0.2.

πŸ› οΈ How to Fix Decimal Precision

βœ”οΈ Option 1: Format with .toFixed()

This formats your result to the number of decimal places you want, but it returns a string, not a number:

let result = (0.1 + 0.2).toFixed(2);
console.log(result); // "0.30"

Instead of working with decimals directly, work in cents or integers, then divide later if needed.

πŸ§‘β€πŸ³ Real-World Example: Shopping Cart Math

let itemPrice = 19.99;
let quantity = Number(document.getElementById("qty").value); // Always a string!
let subtotal = itemPrice * quantity;
let taxRate = 0.08;
let total = (subtotal * (1 + taxRate)).toFixed(2);

console.log(`Total: $${total}`); // "Total: $64.77"

Here, we:

  • Convert the input to a number.

  • Do the calculation

  • Format the final result to 2 decimal places.

⚠️ Pro Tip:

βœ”οΈ Always validate and convert user input before doing math.

βœ”οΈ Be extra careful with decimal calculations β€” decimal precision will trip you up if you trust Javascript to "guess" what you meant πŸ˜‰.

And there you have it β€” the wild world of Javascript types, conversions, and those sneaky decimal quirks.

Stay curious, and let's keep unpacking Javascript together! πŸš€

0
Subscribe to my newsletter

Read articles from Sangy K directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sangy K
Sangy K

An Introvert Coder | Trying to be a Full-stack Developer | A Wannabe Content Creator