Skip to content

Variables & Data Types

JavaScript variables store data values. Modern JavaScript offers three ways to declare variables: var (legacy), let (block-scoped), and const (constant).

Data types include primitives (string, number, boolean, null, undefined, symbol, bigint) and objects (including arrays, functions).

// Variable declarations
let age = 25; // mutable
const name = "Alice"; // immutable
var legacy = "old"; // function-scoped (avoid)
// Data types
let text = "Hello"; // string
let count = 42; // number
let price = 19.99; // number (no separate float)
let isValid = true; // boolean
let empty = null; // null
let notDefined; // undefined
let id = Symbol("id"); // symbol
let huge = 123n; // bigint
// Objects
let user = { name: "Bob", age: 30 };
let colors = ["red", "green", "blue"];

Using var instead of let/const causes scope issues:

// BAD - var has function scope
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3
// GOOD - let has block scope
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 0, 1, 2

Fix: Always use let or const instead of var.

  1. What’s the difference between let and const?

    Answer`let` allows reassignment; `const` prevents reassignment (but object properties can still change).
  2. What does typeof null return?

    Answer`"object"` (this is a known JavaScript quirk).
  3. Declare a constant array and add an item to it. Does this work?

    AnswerYes! `const arr = []; arr.push(1);` works because `const` prevents reassignment, not mutation.