JavaScript Basics
Variables & Data Types
Foundation concepts of JavaScript — how the language stores values, and the rules that decide what a variable is allowed to hold.
ES2023
✓ Beginner Friendly
2 Topics
01
var, let & const
JavaScript has three ways to declare a variable, and they don't behave the same way. var is function-scoped and hoisted with an undefined placeholder. let and const are block-scoped and live in a "temporal dead zone" until their line runs — reference them earlier and JS throws instead of silently returning undefined.
JavaScript — Declarations
// var — function-scoped, hoisted, can be redeclared var x = 10; var x = 20; // no error // let — block-scoped, reassignable, no redeclare in same scope let age = 25; age = 26; // OK // const — block-scoped, cannot be reassigned const name = "Ada"; // name = "Grace"; // TypeError: Assignment to constant variable // Block scope demo — var leaks, let/const don't { var a = 1; let b = 2; } console.log(a); // 1 — leaked out of the block // console.log(b); // ReferenceError: b is not defined
Which One to Use
✓ Default choice
const— for anything not reassignedlet— when the value will change- Both are block-scoped, no surprises
✗ Avoid in new code
var— function-scoped leaks bugs- Hoisting makes
varread before assign - Silently redeclarable — easy to shadow by accident
const doesn't mean immutable:
const arr = [1,2]; arr.push(3); works fine — const only locks the binding, not the object's contents. Use Object.freeze() for real immutability.02
Data Types & Coercion
| Type | typeof | Example | Notes |
|---|---|---|---|
| Number | "number" | let n = 25; | No separate int/float — all one 64-bit float |
| String | "string" | let s = "Ada"; | Immutable, use template literals for interpolation |
| Boolean | "boolean" | let ok = true; | true / false |
| undefined | "undefined" | let x; | Declared, never assigned |
| null | "object" | let x = null; | Intentional "no value" — typeof is a famous quirk |
| BigInt | "bigint" | 10n | Integers beyond 2^53 safely |
| Symbol | "symbol" | Symbol("id") | Unique, mostly for object keys |
JavaScript — Template Literals & Coercion
const name = "Ada", age = 36; // Template literals — backticks, ${} interpolation, multi-line console.log(`${name} is ${age} years old`); // == does type coercion, === does not — always prefer === 1 == "1" // true — string coerced to number 1 === "1" // false — different types 0 == false // true null == undefined // true — special-cased null === undefined // false
Falsy values (only 6):
false, 0, "", null, undefined, NaN. Everything else — including "0", [], and {} — is truthy.✓
Quick Quiz
1. Which declaration is block-scoped and reassignable?
2. typeof null returns…
3. Which value is falsy?
4. 1 === "1" evaluates to…
5. const arr = [1]; arr.push(2); — result?