C
JavaScript/Basics/Lesson 03

Variables — let · const · var

45 min·theory
This chapter
2/5

Variables — let · const · var

🎯 After reading this lesson

After reading this lesson, you will be able to confidently do the following 3 things.

  • ✅ Why var is dangerous (function scope · hoisting)
  • ✅ What TDZ (Temporal Dead Zone) is
  • ✅ How to choose between const / let based on reassignment needs

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

What is a variable?

The Core in One Line

Variable = a container that stores a value under a name. JS has 3 keywords — var·let·const — which coexist for historical reasons. Bottom line: const first, let when needed, never var.

const — Set Once, Done

javascript
const PI = 3.14;
PI = 3.15;   // ❌ TypeError: Reassignment not allowed

The most frequently used keyword. 95% of variables are fine with const. Reassignment is usually unnecessary.

> ⚠️ Common confusion: const only prohibits reassignmentinternal modification is still allowed:

javascript
const obj = { name: "Hong" };
obj.name = "Gildong";              // ✅ OK — modifying *internal* property of object
console.log(obj);                // { name: "Gildong" }   ← changed!

// obj = { other: "X" };         // ❌ TypeError: Assignment to constant variable
//
// 💡 const = cannot change "the address the variable points to"
//    Internal contents of the object are a different matter → can be freely modified

let — When You Truly Need to Change the Value

javascript
let count = 0;                       // 🔓 Mutable variable

for (let i = 0; i < 10; i++) {       // i = 0,1,2,3,...,9
    count = count + i;               // Accumulate (0+1+2+...+9)
}

console.log(count);   // 45   ← Sum of 0+1+2+...+9

For loop counters, running totals, and other cases where the value must change. Start with const and switch to let only when truly necessary.

var — The Old Keyword, Don't Use It

javascript
var x = 10;   // ❌

Before 2015, JS only had var. But:

  • Function scope — a declaration inside if applies to the entire function
  • Hoisting — can be used regardless of declaration position (causes confusion)
  • Re-declaration allowed — declaring the same name twice produces no error

These unpredictable traits cause bugs. You'll only see it in legacy code now.

Block Scope — The Real Value of let·const

javascript
function example() {
    if (true) {
        // 🔲 Block start — inside { }
        let x = 10;       // 📦 Lives only within the block
        const y = 20;     // 📦 Lives only within the block
        var z = 30;       // 🌐 var ignores blocks → lives throughout the entire function
    }
    // 🔲 Block end — outside }

    console.log(z);   // 30   ← ✅ Accessible outside if because it's var
    console.log(x);   // 💥 ReferenceError: x is not defined
    //                       (let only lives inside the block, so it's already dead)
}

example();   // ▶️ Calling it makes the above code actually run!

let·const are only valid within the block ({}) they are declared in. This means predictable behavior + no variable name collisions.

Naming Conventions

javascript
// camelCase — Recommended
const userName = "Hong Gil-dong";
const isActive = true;
const userList = [];

// PascalCase — Classes·Components
class User {}
function MyComponent() {}

// UPPER_CASE — Constants
const MAX_RETRIES = 3;
const API_URL = "https://api.example.com";

Quick Summary

javascript
// 99% of cases
const userName = "Hong Gil-dong";

// Loops·Reassignment needed
let count = 0;

// var — Never

Start with const and switch to let only when you truly need to.

⚡ Try It Yourself — const · let · var

Work directly with const and let, and see what errors appear when you attempt reassignment.
✏️ JS 코드
📟 Console output
▶ Press the Run button
⚠️ Runs in a browser sandbox — only console.log() is supported; alert/fetch are not.

🤖 Try Asking AI Like This

Once you know the concepts in this lesson, you can give AI specific instructions. Instead of a vague 'fix this,' you can make requests with vocabulary — and that is where token savings begin.

  • "Replace all var in this code with const/let"
  • "Analyze reassignment possibilities and reorganize with const as the default"
  • "Diagnose potential hoisting issues in this code"

Why This Reduces Tokens

Without knowing the concepts, even after receiving an AI response you have to ask 'What does that mean?' again. That follow-up question is what consumes tokens. Learn the concept once, and the conversation ends in a single exchange.

Read this first: What is JavaScript?
Up next: Data Types
Variables (var, let, const) - JavaScript