📦 JavaScript Fundamentals⏱ 45–60 min🟢 Beginner

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
1

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.

basics.js
// 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
Note

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
⚠️ What About var?

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.

2

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.

all-types.js
// ── 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}`;
📝stringprimitive
"Alex"
'alex@email.com'

Text. Use backtick template literals for interpolation: `Hi ${name}`

🔢numberprimitive
22
3.14
NaN

Integers AND floats are both number. NaN ("Not a Number") has typeof "number".

🔭bigintprimitive
9007199254740993n

For integers larger than Number.MAX_SAFE_INTEGER. Append n suffix or use BigInt().

✅booleanprimitive
true
false

Only two values. Used for flags: isLoggedIn, isPremium.

❓undefinedprimitive
undefined

JavaScript's default. A declared-but-not-assigned variable holds undefined. Missing function params are undefined.

🚫nullprimitive
null

Intentional absence. Set by the developer to say "this has no value yet". typeof null === "object" is a JS quirk.

🔑symbolprimitive
Symbol("id")

Guaranteed unique identifier. Each Symbol() call creates a new, unique value. Rarely needed in everyday code.

📦objectreference
{ id: 1, name: "Alex" }

Collection of key-value pairs. Arrays and functions are also objects under the hood in JavaScript.

📋arrayreference
["JS", "React"]

Ordered list. typeof [] === "object". Use Array.isArray(value) to detect arrays specifically.

3

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.

Expressiontypeof resultNotes
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
⚠️ The null Quirk

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.

4

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.value is always a string
  • URL param: searchParams.get("page") is a string
  • API response: may return "true" instead of true
type-conversion.js
// ── 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
💡 Rule of Thumb

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.

5

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.

📦 User Profile LabLive JavaScript execution
Output
Click ▶ Run to see output
6

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.

🐛 Type Bug Debugging Lab
Read the buggy code → run it → fix it  | 0/6 fixed

A developer stores a score in const and then tries to update it. What goes wrong?

Output
Click ▶ Run to see what happens
1 / 6
7

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 age and credits to numbers
  • Convert isVerified to a real boolean
  • Decide which variables should be const and which should be let
  • Print a clean user summary with correct types

Flow: Inspect → Choose Types → Write Code → Run → Debug → Validate → Show Solution

🎯 User Registration ChallengeComplete all 4 tasks
Output
Click ▶ Run to see output
8

Recap — Key Concepts

Variable

A named binding used to hold/reference a value in memory.

const

Binding cannot be reassigned. Default choice in modern JS.

let

Binding can be reassigned. Use only when you need to update the value.

Primitives

string, number, bigint, boolean, undefined, null, symbol. Stored by value.

Object

Collection of related key-value pairs. Stored and compared by reference.

Array

Ordered list of values. Technically an object. Use Array.isArray() to detect.

typeof

Operator that returns the runtime type category as a string.

null

Intentional absence of a value. Set by the developer. typeof null === "object" is a quirk.

undefined

JavaScript's default "nothing". A variable declared but not assigned.

Type Conversion

Explicitly change a value's type: Number(), String(), Boolean().

Implicit Coercion

JavaScript automatically converts types in expressions like "5" + 10 → "510".

NaN

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)