Variables & Data Types

📖 Concept

In JavaScript, variables are containers that store data values. Think of them like labeled boxes — you put a value inside and refer to it by the label.

var — The original way to declare variables. Function-scoped and hoisted. Avoid in modern code. let — Block-scoped, can be reassigned. Use when the value will change. const — Block-scoped, cannot be reassigned. Use by default.

JavaScript has 7 primitive data types: string, number, bigint, boolean, undefined, null, symbol, and one non-primitive: object.

🏠 Real-world analogy: Think of const like a permanent marker label on a box — you can change what's inside the box (for objects), but you can't relabel the box. let is like a sticky note — you can peel it off and put a new label.

💻 Code Example

codeTap to expand ⛶
1// Variable declarations
2var oldWay = "I'm function-scoped"; // Avoid in modern JS
3let age = 25; // Can be reassigned
4const name = "Alice"; // Cannot be reassigned
5
6// Data types
7const str = "Hello"; // string
8const num = 42; // number
9const big = 9007199254740991n; // bigint
10const bool = true; // boolean
11const nothing = null; // null (intentional absence)
12let notDefined; // undefined (not yet assigned)
13const sym = Symbol("id"); // symbol
14
15// typeof operator
16console.log(typeof str); // "string"
17console.log(typeof num); // "number"
18console.log(typeof bool); // "boolean"
19console.log(typeof nothing); // "object" ⚠️ This is a famous JS bug!
20console.log(typeof notDefined);// "undefined"
21
22// const with objects — the reference is fixed, not the content
23const user = { name: "Alice" };
24user.name = "Bob"; // ✅ This works! We changed the content, not the box
25// user = {}; // ❌ TypeError: Assignment to constant variable

🏋️ Practice Exercise

Mini Exercise: Create variables to store your personal info:

  1. Use const for your name and birth year
  2. Use let for your current city (you might move!)
  3. Calculate your age from the birth year
  4. Log the type of each variable using typeof
  5. Try reassigning the const name — what happens?

⚠️ Common Mistakes

  • Using var instead of let/constvar is function-scoped and hoisted, leading to bugs

  • Thinking const makes objects immutable — it only prevents reassignment of the variable, not mutation of the object

  • Not knowing typeof null returns "object" — this is a legacy JavaScript bug

  • Forgetting that let and const have a Temporal Dead Zone (TDZ) — accessing them before declaration throws a ReferenceError

  • Confusing undefined (not yet assigned) with null (intentionally empty)

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Variables & Data Types. Login to unlock this feature.