2.2 Module 2 · Variables, Data Types & Functions

Data Types

Understand the kinds of values JavaScript can hold — from simple primitives like numbers and strings, to complex reference types like objects and arrays.

1

Definition

In JavaScript, data types define the kind of value a variable can hold. They determine how data is stored, processed, and what operations can be performed on it. JavaScript has two categories:

Primitive Types — basic, immutable values stored directly: String, Number, Boolean, null, undefined, Symbol, and BigInt.

Non-Primitive Types — complex, reference values stored by address in memory: Object, Array, Function.

2

Simple Way

Data types are like types of containers — each designed to hold a specific kind of value:

Primitive One simple value — a number, text, true/false
Object A labelled collection of values — { name: "Aman", age: 22 }
Array An ordered list of values — ["red", "green", "blue"]
3

Code Examples

Example 1 — Primitive Data Types
let name       = "Aman";        // String
let age        = 22;            // Number
let isStudent  = true;          // Boolean
let emptyValue = null;          // Null
let notAssigned;                // Undefined
let uniqueId   = Symbol("id");  // Symbol

console.log(typeof name);
console.log(typeof age);
console.log(typeof isStudent);
console.log(typeof emptyValue);
console.log(typeof notAssigned);
console.log(typeof uniqueId);
Output
Click ▶ Run to execute
Explanation
  • String → text wrapped in quotes
  • Number → any numeric value (integer or decimal)
  • Boolean → only true or false
  • null → intentionally empty — you set this on purpose
  • undefined → declared but never assigned a value
  • Symbol → a guaranteed unique identifier
Example 2 — Non-Primitive Data Types
let person = {
  name: "Aman",
  age: 22
}; // Object

let colors = ["red", "green", "blue"]; // Array

console.log(typeof person);
console.log(typeof colors);
console.log(Array.isArray(colors)); // better Array check
Output
Click ▶ Run to execute
Explanation
  • Object → stores key-value pairs — the most flexible data structure
  • Array → an ordered list; typeof calls it "object" too
  • Use Array.isArray() to reliably distinguish an array from a plain object
Example 3 — Copy by Value vs Copy by Reference
// Primitives → copied by VALUE
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 — unaffected
console.log(b); // 20

// Objects → copied by REFERENCE
let obj1 = { value: 10 };
let obj2 = obj1;     // both point to the same object
obj2.value = 20;
console.log(obj1.value); // 20 — obj1 changed too!
Output
Click ▶ Run — spot the difference!
Explanation
  • Primitives are copied by value — b = a makes an independent copy
  • Objects are copied by reference — obj2 = obj1 makes both variables point to the same object in memory
  • Changing obj2 therefore also changes obj1
4

Real-Life Example

Think about the difference between a single item and a collection:

String
A name tag — "Aman" — a single piece of text
Number
A price tag — ₹100 — a single numeric value
Boolean
A light switch — only on or off, true or false
null
An empty box — you deliberately left nothing inside
Object
A wallet — holds money, cards, and ID all together
Array
A shopping list — ordered items you can loop through
5

HTML + JavaScript Example

Click ▶ Preview, then press the button inside to check the typeof each variable and display the results live on the page.

Live in Browser — Data Type Checker
<!DOCTYPE html>
<html>
<head><title>Data Types</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Check Data Types</h2>
  <button onclick="checkTypes()"
    style="padding:8px 20px;background:#f7df1e;border:none;
           border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
    Click
  </button>
  <div id="output" style="margin-top:16px;line-height:2.2;font-size:0.95rem"></div>

  <script>
    function checkTypes() {
      let name      = "Aman";
      let age       = 22;
      let isStudent = true;
      let empty     = null;
      let colors    = ["red", "green", "blue"];
      let person    = { name: "Aman", age: 22 };

      const row = (label, val) =>
        `<b>${label}</b> → <code>typeof</code> = <b style="color:#e07b00">${typeof val}</b><br>`;

      document.getElementById("output").innerHTML =
        row("name",      name)      +
        row("age",       age)       +
        row("isStudent", isStudent) +
        row("null",      empty)     +
        row("colors []", colors)    +
        row("person {}", person);
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Identify your types
Starter code
let name      = "Your Name";
let age       = 0;
let isLearning = true;
  • Replace the values with your own name, age, and learning status
  • Print each variable's type using typeof
  • Confirm: name → string, age → number, isLearning → boolean
Medium Task 2 — Student object & subjects array
Starter code
const student = { name: "Priya", marks: 88 };
const subjects = ["Maths", "Science", "English"];
  • Log typeof student and typeof subjects — notice both say "object"
  • Use Array.isArray(subjects) to correctly detect the array
  • Print student.name and subjects[0]
7

MCQs

Q1
Which of these is not a primitive data type?
  • A String
  • B Number
  • C Object
  • D Boolean
💡 C is correct. Object is a non-primitive (reference) type. String, Number, and Boolean are all primitives — they hold a single immutable value.
Q2
What does typeof null return?
console.log(typeof null);
Output
Run it to verify
  • A "null"
  • B "undefined"
  • C "object"
  • D "number"
💡 C is correct. typeof null === "object" is a well-known JavaScript bug that has existed since its first version and was never fixed to preserve backwards compatibility.
Q3
What does typeof [] return?
console.log(typeof []);
console.log(Array.isArray([]));
Output
Run it to verify
  • A "array"
  • B "object"
  • C "list"
  • D "undefined"
💡 B is correct. Arrays are technically objects in JavaScript, so typeof [] returns "object". Use Array.isArray() whenever you need to tell them apart.
8

Pro Tips & Extra Knowledge

  • 01

    typeof null returns "object" — a historic JavaScript bug. To check for null, always compare directly:

    Correct null check
    let val = null;
    
    console.log(typeof val);     // "object" — misleading!
    console.log(val === null);   // true  — correct check
    Output
    Click ▶ Run to execute
  • 02

    Use Array.isArray() instead of typeof to reliably detect arrays:

    Detecting arrays correctly
    let arr = [1, 2, 3];
    
    console.log(typeof arr);          // "object" — not helpful
    console.log(Array.isArray(arr));  // true  — reliable
    Output
    Click ▶ Run to execute
  • 03

    Know the difference between undefined and null — they look similar but mean different things:

    undefined vs null
    let x;          // undefined — declared, never assigned
    let y = null;   // null — deliberately set to empty
    
    console.log(x); // undefined
    console.log(y); // null
    console.log(x == y);  // true  (loose equality)
    console.log(x === y); // false (strict equality)
    Output
    Click ▶ Run to execute
  • 04

    You can mutate the properties of a const object — you just can't replace the object itself:

    const object mutation
    const user = { name: "Aman" };
    user.name = "Raj";  // allowed — property changed
    console.log(user.name);
    
    // user = {};  // Error — cannot reassign the binding
    Output
    Click ▶ Run to execute
Mini Challenge

Predict both outputs before running — remember the typeof null quirk!

What does this print?
let x = null;
let y;

console.log(typeof x);
console.log(typeof y);
Output
Think first, then run!
Step-by-Step Explanation
// Step 1: let x = null
//         x holds the value null (intentionally empty)

// Step 2: typeof x
//         Expected: "null" — Actual: "object"
//         This is a historic JavaScript bug (since 1995).
//         null is NOT an object, but typeof reports it as one.
//         Output → "object"

// Step 3: let y;
//         y is declared but never assigned — its value is undefined

// Step 4: typeof y
//         typeof undefined === "undefined"
//         Output → "undefined"

// Final output:
//   "object"     ← the typeof null bug
//   "undefined"  ← declared but unassigned

// Key takeaway:
//   To check for null → use (x === null), not typeof
//   To check for undefined → typeof y === "undefined" works fine