Home

JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법

Published in javascript
December 31, 2025
4 min read
JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법

Hey there, fellow coders! It’s your friendly neighborhood “Coding Bear” here, back with another deep dive into the wild world of JavaScript. Today, we’re tackling a topic that seems simple on the surface but is absolutely fundamental to writing clean, predictable, and bug-free code: variable declaration. If you’ve ever been confused about when to use var, let, or const, or if you’ve encountered mysterious bugs related to variable scope, this guide is for you. We’re going to break down the history, the behavior, and the modern best practices so you can declare your variables with confidence. Let’s get started!

The Legacy of var: Function-Scoped and Hoisted

In the early days of JavaScript, var was the only way to declare a variable. Understanding its behavior is key to understanding why let and const were introduced in ES6 (ECMAScript 2015). 1. Function Scope: Variables declared with var are function-scoped. This means they are accessible anywhere within the function they are declared in. If declared outside any function, they become globally scoped.

function varExample() {
if (true) {
var functionScoped = "I'm inside an if block";
}
console.log(functionScoped); // Output: "I'm inside an if block" - Accessible!
}
varExample();
console.log(functionScoped); // ReferenceError: functionScoped is not defined

Notice how functionScoped is accessible outside the if block but still inside the function. This lack of block-level scoping often led to unintended behavior and bugs. 2. Hoisting: var declarations are hoisted to the top of their function or global scope. However, only the declaration is hoisted, not the initialization. The variable exists from the start of its scope but has the value undefined until the assignment line is reached.

console.log(hoistedVar); // Output: undefined (not a ReferenceError!)
var hoistedVar = "Now I'm defined";
console.log(hoistedVar); // Output: "Now I'm defined"

This behavior can be confusing, as it allows you to reference a variable before its declaration line, often leading to logical errors. 3. Re-declaration and Re-assignment: You can re-declare and re-assign a var variable multiple times within its scope.

var x = 10;
var x = 20; // Re-declaration is allowed
console.log(x); // 20
x = 30; // Re-assignment is allowed
console.log(x); // 30

This flexibility can make code harder to maintain, as it allows accidental overwrites.

JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법
JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법


🎮 If you’re curious about various subjects and technologies, Python NameError How to Fix Variable Not Defined Errors Like a Profor more information.

The Modern Saviors: let and const (Block Scoping)

ES6 introduced let and const to address the quirks of var and provide more predictable scoping rules. 1. Block Scope: Both let and const are block-scoped. A block is any code wrapped in curly braces {} (e.g., if, for, while, or a standalone block {}). A variable declared inside a block is only accessible within that block and any nested blocks.

function letConstExample() {
if (true) {
let blockScopedLet = "I'm let";
const blockScopedConst = "I'm const";
console.log(blockScopedLet); // Works
console.log(blockScopedConst); // Works
}
// console.log(blockScopedLet); // ReferenceError!
// console.log(blockScopedConst); // ReferenceError!
}
letConstExample();

This containment prevents variables from “leaking” out of their intended context, a significant improvement over var. 2. The Temporal Dead Zone (TDZ): A critical concept for let and const is the Temporal Dead Zone. It refers to the period between the start of the block and the point where the variable is declared. Accessing the variable in the TDZ results in a ReferenceError.

{
// Start of TDZ for 'temporalVar'
console.log(temporalVar); // ReferenceError: Cannot access 'temporalVar' before initialization
let temporalVar = "Out of the TDZ";
// End of TDZ
}

This makes the error explicit and catchable during development, unlike the silent undefined from a hoisted var. 3. let vs. const: The Key Difference The primary distinction is in re-assignment.

  • let: Allows re-assignment. You cannot re-declare it within the same scope.
    let counter = 0;
    counter = 1; // Re-assignment: OK
    // let counter = 2; // SyntaxError: Identifier 'counter' has already been declared
  • const: Stands for constant. It must be assigned a value at declaration and cannot be re-assigned. It also cannot be re-declared.
    const PI = 3.14159;
    // PI = 3.14; // TypeError: Assignment to constant variable.
    // const PI = 3.14; // SyntaxError: Identifier 'PI' has already been declared
    const user = { name: "Bear" };
    user.name = "Coding Bear"; // This is OK! We are mutating the object's property.
    // user = { name: "New Bear" }; // TypeError: Assignment to constant variable.
    Crucial Note: const does not make the value immutable, only the binding. For objects and arrays, the contents can be changed (mutated), but you cannot point the variable to a completely new object or array.

JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법
JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법


💬 Real opinions from real diners — here’s what they had to say about Healthy Substance to see what makes this place worth a visit.

Head-to-Head Comparison and Best Practices

Let’s put it all together in a definitive comparison table and establish modern JavaScript best practices. | Feature | var | let | const | | :--- | :--- | :--- | :--- | | Scope | Function or Global | Block | Block | | Hoisting | Yes (initialized as undefined) | Yes (but in TDZ) | Yes (but in TDZ) | | Re-declaration | Allowed | Not allowed | Not allowed | | Re-assignment | Allowed | Allowed | Not allowed | | Initial Value | Optional (defaults to undefined) | Optional | Required | | Use Case | Legacy code, specific patterns | Variables that need to change | Variables that shouldn’t be re-assigned | Modern JavaScript Best Practices from Coding Bear:

  1. Default to const: Start every variable declaration with const. This is the most important rule. It signals intent that this identifier’s reference won’t change, making code easier to reason about.
  2. Use let when you know the value will change: If you need to re-assign a variable (e.g., loop counters, accumulators, state variables), use let.
  3. Avoid var in new code: There is almost no reason to use var in modern ES6+ code. Its function-scoping and hoisting behavior are more likely to introduce bugs than provide benefit. Use let and const exclusively.
  4. Declare variables at the point of use: Thanks to block scoping and TDZ, you can (and should) declare variables as close as possible to where they are first used. This improves readability.
  5. Use descriptive names: This is always good practice, but with const, it becomes even more critical as the name often describes an immutable concept or value in your program. By following these practices, you’ll write JavaScript that is more robust, less prone to scope-related bugs, and clearer for other developers (including your future self) to understand.

JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법
JavaScript 변수 선언 완벽 가이드 var, let, const의 차이점과 올바른 사용법


✨ For food lovers who appreciate great taste and honest feedback, La Esquina to see what makes this place worth a visit.

And there you have it! The journey from the wild west of var to the structured, predictable world of let and const. Embracing block scoping and preferring const is one of the simplest yet most powerful steps you can take to level up your JavaScript code quality. It reduces cognitive load, prevents entire categories of errors, and aligns with the practices used in modern frameworks and libraries. Remember, as the “Coding Bear,” I believe great code is built on strong fundamentals. Mastering variable declaration is a cornerstone of that foundation. Now go forth and declare your variables with purpose! Feel free to roar in the comments if you have any questions or insights to share. Happy coding

🥂 Whether it’s date night or brunch with friends, don’t miss this review of Quarter Sheets Pizza Club to see what makes this place worth a visit.









Take your first step into the world of Bitcoin! Sign up now and save on trading fees! bitget.com Quick link
Take your first step into the world of Bitcoin! Sign up now and save on trading fees! bitget.com Quick link




Tags

#developer#coding#javascript

Share

Previous Article
Demystifying the TypeError unsupported operand type(s) in Python A Comprehensive Guide for Developers

Related Posts

Mastering JavaScript Error Handling A Deep Dive into try...catch for Robust Code
December 24, 2025
4 min