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
1// Variable declarations2var oldWay = "I'm function-scoped"; // Avoid in modern JS3let age = 25; // Can be reassigned4const name = "Alice"; // Cannot be reassigned56// Data types7const str = "Hello"; // string8const num = 42; // number9const big = 9007199254740991n; // bigint10const bool = true; // boolean11const nothing = null; // null (intentional absence)12let notDefined; // undefined (not yet assigned)13const sym = Symbol("id"); // symbol1415// typeof operator16console.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"2122// const with objects — the reference is fixed, not the content23const user = { name: "Alice" };24user.name = "Bob"; // ✅ This works! We changed the content, not the box25// user = {}; // ❌ TypeError: Assignment to constant variable
🏋️ Practice Exercise
Mini Exercise: Create variables to store your personal info:
- Use
constfor your name and birth year - Use
letfor your current city (you might move!) - Calculate your age from the birth year
- Log the type of each variable using
typeof - Try reassigning the
constname — what happens?
⚠️ Common Mistakes
Using
varinstead oflet/const—varis function-scoped and hoisted, leading to bugsThinking
constmakes objects immutable — it only prevents reassignment of the variable, not mutation of the objectNot knowing
typeof nullreturns"object"— this is a legacy JavaScript bugForgetting that
letandconsthave a Temporal Dead Zone (TDZ) — accessing them before declaration throws a ReferenceErrorConfusing
undefined(not yet assigned) withnull(intentionally empty)
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Variables & Data Types. Login to unlock this feature.