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:
- Primitives: Simple values like
Number,String,Boolean,Undefined, andNull. These are stored "By Value." - Objects: Complex structures like
ArraysandObjects. 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
- Null typeof: Checking
typeof nullreturns"object". To check for null, usemyVar === null. - Number Precision: JavaScript uses "Floating Point" math.
0.1 + 0.2is actually0.30000000000000004. Never use JS for high-precision financial calculations without a special library! - Comparing Objects:
[1,2] === [1,2]is false! You cannot compare objects directly with===because they are different references in memory.
Practice Exercises
- The Type Checker: Write 10 different variables and use a loop to print the
typeofeach one. - The Reference Trap: Create an array
a = [1]. Setb = a. Push a number intoaand see what happens tob. - The Precision Fix: Research the
.toFixed(2)method and use it to fix the0.1 + 0.2math problem.