Data Types: Primitives vs Objects

Data Types: Primitives vs Objects in JavaScript: JavaScript is "Dynamically Typed." You don't have to tell the computer that a variable is a "Number." It…

Concept Explanation

JavaScript is "Dynamically Typed." You don't have to tell the computer that a variable is a "Number." It figures it out automatically.

There are two main categories:

  1. Primitives: Simple values like Number, String, Boolean, Undefined, and Null. These are stored "By Value."
  2. Objects: Complex structures like Arrays and Objects. These are stored "By Reference" (like a link to a location in memory).

Syntax or Core Structure

Checking Types

Use the typeof operator to see what you are working with.

console.log(typeof 42);         // "number"
console.log(typeof "Hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (This is a famous bug in JS!)

The Null vs Undefined Mystery

  • undefined: "The variable exists, but no value was ever put in the box." (Automated)
  • null: "I am intentionally putting 'nothing' in the box." (Manual)

Real World Example

A User Profile: Imagine a social media app.

  • userName: String ("Alice")
  • followerCount: Number (1200)
  • isOnline: Boolean (true)
  • bio: Null (The user hasn't written one yet)
  • address: Undefined (The app hasn't even asked for it yet)

Common Mistakes

  1. Null typeof: Checking typeof null returns "object". To check for null, use myVar === null.
  2. Number Precision: JavaScript uses "Floating Point" math. 0.1 + 0.2 is actually 0.30000000000000004. Never use JS for high-precision financial calculations without a special library!
  3. Comparing Objects: [1,2] === [1,2] is false! You cannot compare objects directly with === because they are different references in memory.

Practice Exercises

  1. The Type Checker: Write 10 different variables and use a loop to print the typeof each one.
  2. The Reference Trap: Create an array a = [1]. Set b = a. Push a number into a and see what happens to b.
  3. The Precision Fix: Research the .toFixed(2) method and use it to fix the 0.1 + 0.2 math problem.