Variables & Data Types
Storing Data in JavaScript
Every program stores information — usernames, ages, prices, lists of items. JavaScript gives you variables to name and hold that data, and a type system that describes what kind each value is. This module covers the complete foundation: declaring variables correctly, understanding all seven primitive types plus reference types, inspecting types at runtime, and converting between them safely.
🎯 What You Will Learn
- Declare variables with let and const (and why not var)
- Understand all 7 primitives: string, number, bigint, boolean, undefined, null, symbol
- Work with reference types: object, array, function
- Inspect runtime types using typeof (including the null quirk)
- Convert values: Number(), String(), Boolean()
- Avoid implicit coercion bugs from form inputs and APIs
- Debug the most common type-related beginner mistakes
- Complete a real user registration data challenge
Variables — Naming Data in Your Program
What Is a Variable?
A variable is a named binding that holds a value in memory. You give it a name, and JavaScript keeps track of what is stored under that name. You can read the value, and (depending on which keyword you used) update it later.
// Declaring and assigning const username = "Alex"; // cannot be reassigned let score = 80; // can be reassigned // Reading values console.log(username); // "Alex" console.log(score); // 80 // Updating a value score = 95; console.log(score); // 95
const — Fixed Binding
The binding cannot be reassigned. This is the default choice in modern JS.
- Username set at registration
- API endpoint URL
- User ID returned from the server
- A configuration object
const does NOT make objects/arrays immutable. You can still mutate their contents — you just cannot point the variable at a different object.
let — Reassignable
Use let only when you specifically need to reassign the variable later.
- A score counter that increments
- A loading state:
let isLoading = true - A loop counter
- Credits that can be spent
Older JavaScript code uses var. It is function-scoped (not block-scoped), can be re-declared without error, and gets hoisted in unexpected ways. Modern code — including all React, Node.js, Express, and Next.js projects — uses let and const exclusively. Don't use var in new code.
JavaScript Data Types
Primitives vs Reference Types
JavaScript has two categories of types. Primitives are simple, immutable values — stored and compared by value. Reference types (objects) store a reference (pointer) to data in memory — two variables can point at the same object.
// ── Primitives ───────────────────────────────────── const username = "Alex"; const age = 22; const bigNum = 9007199254740993n; const isLoggedIn = true; const profile = null; let token; // undefined const uid = Symbol("user") // ── Reference types ──────────────────────────────── const skills = ["JavaScript", "React"]; // Array const user = { id: 1, name: "Alex" }; // Object const greet = (name) => `Hi ${name}`;
Text. Use backtick template literals for interpolation: `Hi ${name}`
Integers AND floats are both number. NaN ("Not a Number") has typeof "number".
For integers larger than Number.MAX_SAFE_INTEGER. Append n suffix or use BigInt().
Only two values. Used for flags: isLoggedIn, isPremium.
JavaScript's default. A declared-but-not-assigned variable holds undefined. Missing function params are undefined.
Intentional absence. Set by the developer to say "this has no value yet". typeof null === "object" is a JS quirk.
Guaranteed unique identifier. Each Symbol() call creates a new, unique value. Rarely needed in everyday code.
Collection of key-value pairs. Arrays and functions are also objects under the hood in JavaScript.
Ordered list. typeof [] === "object". Use Array.isArray(value) to detect arrays specifically.
typeof — Identifying Values at Runtime
Inspecting an Unknown Value
typeof value returns a string describing the type category. It is your go-to tool when you receive data from a form, URL, API, or external function and need to know what you are working with.
| Expression | typeof result | Notes |
|---|---|---|
| typeof "Hello" | "string" | |
| typeof 42 | "number" | |
| typeof NaN | "number" ⚠️ | NaN is technically a number |
| typeof 42n | "bigint" | |
| typeof true | "boolean" | |
| typeof undefined | "undefined" | |
| typeof null | "object" ⚠️ | Historical JS bug — null is NOT an object |
| typeof Symbol() | "symbol" | |
| typeof {} | "object" | |
| typeof [] | "object" ⚠️ | Use Array.isArray() to detect arrays |
| typeof function(){} | "function" | Functions are objects but get a special result |
typeof null === "object" is a bug introduced in JavaScript in 1995 and never fixed to preserve backward compatibility. null is NOT an object — it is a primitive. Always check for null explicitly: value === null.
Values & Type Conversion
Why Type Conversion Matters
When data arrives from forms, URL parameters, or JSON APIs, it often comes as a string — even if it represents a number or boolean. Treating "42" (string) the same as 42 (number) is a classic bug:
- Form field:
input.valueis always a string - URL param:
searchParams.get("page")is a string - API response: may return
"true"instead oftrue
// ── String → Number ────────────────────────────── Number("42") // → 42 Number("3.14") // → 3.14 Number("hello") // → NaN ← invalid! // ── Number → String ────────────────────────────── String(42) // → "42" (42).toString() // → "42" // ── Any → Boolean ──────────────────────────────── Boolean(0) // → false (0 is falsy) Boolean("") // → false (empty string is falsy) Boolean(null) // → false Boolean("hello") // → true Boolean(42) // → true // ── Implicit coercion (JS does this automatically) "5" + 10 // → "510" ← string concat, NOT addition! "5" - 3 // → 2 ← JS converts "5" for subtraction // ← Prefer explicit conversion to avoid surprises
Always convert form inputs and API data explicitly before using them in calculations. const age = Number(formInput) is clear. Relying on implicit coercion (formInput * 1) is confusing for other developers.
Code Lab — User Profile Program
Build a small User Profile program. The starter code is already working — run it first. Then complete the commented task, experiment with the values, and observe how types affect the output.
Debugging — Common Type Mistakes
Each scenario contains a real bug beginners make with JavaScript types. Read the code, run it to see what happens (or what error is thrown), then click 🔧 Show Fix to see the corrected version and explanation.
A developer stores a score in const and then tries to update it. What goes wrong?
Mini Challenge — User Registration Data
🎯 The Scenario
A registration form submitted its data as raw JSON. All values are strings — even the ones that should be numbers or booleans. Your job is to:
- Inspect each current type with
typeof - Convert
ageandcreditsto numbers - Convert
isVerifiedto a real boolean - Decide which variables should be
constand which should belet - Print a clean user summary with correct types
Flow: Inspect → Choose Types → Write Code → Run → Debug → Validate → Show Solution
Recap — Key Concepts
A named binding used to hold/reference a value in memory.
Binding cannot be reassigned. Default choice in modern JS.
Binding can be reassigned. Use only when you need to update the value.
string, number, bigint, boolean, undefined, null, symbol. Stored by value.
Collection of related key-value pairs. Stored and compared by reference.
Ordered list of values. Technically an object. Use Array.isArray() to detect.
Operator that returns the runtime type category as a string.
Intentional absence of a value. Set by the developer. typeof null === "object" is a quirk.
JavaScript's default "nothing". A variable declared but not assigned.
Explicitly change a value's type: Number(), String(), Boolean().
JavaScript automatically converts types in expressions like "5" + 10 → "510".
Not a Number. Returned by Number("hello"). typeof NaN === "number". Use Number.isNaN() to detect.
Final Mental Model
// How data flows through a full stack application
Value (from user / API / DB)
↓
Variable (named in JS: const / let)
↓
Type Check (typeof / Array.isArray / === null)
↓
Type Conversion (Number / String / Boolean)
↓
Application Logic (if / for / function)
↓
Output (UI / API response / Database write)