πŸ’» Programming

Variable

Variable

A name attached to a memory location that stores data in a program. Understanding the differences between let, const, and var and scope lets you write stable, predictable code.

πŸ“– Detailed Explanation

A variable is a name attached to a memory location used to store and reference data in a program. It means "a value that can change," so its value can change while the program runs. For example, if you declare let count = 0;, the value 0 is stored somewhere in memory, and we can access and change that value through the name "count". Variables are the most fundamental concept in programming and are essential in every language.

Scope refers to the range in which a variable can be accessed. A variable in global scope can be accessed from anywhere in the program, while a variable in local scope can only be accessed inside the function where it is declared. Block scope, introduced in ES6, is valid only inside { } curly braces. JavaScript's let and const follow block scope, but var follows function scope, which can cause unintended bugs.

The differences between let, const, and var in JavaScript are very important. var is the pre-ES6 way of declaring variables; it has function scope and is initialized to undefined when hoisted. let has block scope and is hoisted, but accessing it before initialization causes a TDZ (Temporal Dead Zone) error. const follows the same scope rules as let, but it must be initialized at declaration and cannot be reassigned. However, the inner values of an object or array can be changed.

A naming convention directly affects the readability and maintainability of code. In JavaScript, camelCase is used, and in Python, snake_case is used. A variable name should clearly indicate its role. elapsedTimeInDays is better than d, and currentTemperature is better than temp. Avoid abbreviations, and starting boolean variables with is/has/can, as in isActive and hasPermission, makes their meaning clear.

πŸ’» Code Example

JavaScript - Differences between let, const, and var
// 1. var - ν•¨μˆ˜ μŠ€μ½”ν”„, ν˜Έμ΄μŠ€νŒ… μ‹œ undefined둜 μ΄ˆκΈ°ν™”
console.log(varVariable);  // undefined (μ—λŸ¬ μ•„λ‹˜!)
var varVariable = "var둜 μ„ μ–Έ";

// 2. let - 블둝 μŠ€μ½”ν”„, TDZ 쑴재
// console.log(letVariable);  // ReferenceError: TDZ
let letVariable = "let으둜 μ„ μ–Έ";

// 3. const - μž¬ν• λ‹Ή λΆˆκ°€, 객체 λ‚΄λΆ€λŠ” λ³€κ²½ κ°€λŠ₯
const PI = 3.14159;
// PI = 3.14;  // TypeError: μž¬ν• λ‹Ή λΆˆκ°€

const user = { name: "κΉ€κ°œλ°œ", age: 25 };
user.age = 26;  // 객체 λ‚΄λΆ€ 변경은 κ°€λŠ₯!
console.log(user);  // { name: "κΉ€κ°œλ°œ", age: 26 }

// 4. μŠ€μ½”ν”„ 비ꡐ
function scopeExample() {
    if (true) {
        var functionScoped = "var: ν•¨μˆ˜ μŠ€μ½”ν”„";
        let blockScoped = "let: 블둝 μŠ€μ½”ν”„";
    }
    console.log(functionScoped);  // "var: ν•¨μˆ˜ μŠ€μ½”ν”„"
    // console.log(blockScoped);  // ReferenceError
}

// 5. for λ£¨ν”„μ—μ„œμ˜ 차이 (ν΄λ‘œμ € 문제)
for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log("var:", i), 100);
}  // 좜λ ₯: 3, 3, 3 (μ˜λ„μΉ˜ μ•Šμ€ κ²°κ³Ό!)

for (let j = 0; j < 3; j++) {
    setTimeout(() => console.log("let:", j), 100);
}  // 좜λ ₯: 0, 1, 2 (μ˜λ„ν•œ κ²°κ³Ό)
JavaScript - Scope Chain and Closures
// 1. μ „μ—­ λ³€μˆ˜ (κ°€λŠ₯ν•˜λ©΄ ν”Όν•˜κΈ°)
let globalCount = 0;  // μ–΄λ””μ„œλ“  μ ‘κ·Ό κ°€λŠ₯ - μœ„ν—˜!

// 2. μ§€μ—­ λ³€μˆ˜μ™€ μŠ€μ½”ν”„ 체인
const outerValue = "μ™ΈλΆ€";

function outer() {
    const middleValue = "쀑간";

    function inner() {
        const innerValue = "λ‚΄λΆ€";
        // μŠ€μ½”ν”„ 체인: inner -> outer -> global
        console.log(innerValue);   // "λ‚΄λΆ€" (μžμ‹ μ˜ μŠ€μ½”ν”„)
        console.log(middleValue);  // "쀑간" (μ™ΈλΆ€ μŠ€μ½”ν”„)
        console.log(outerValue);   // "μ™ΈλΆ€" (μ „μ—­ μŠ€μ½”ν”„)
    }

    inner();
}

// 3. ν΄λ‘œμ €λ₯Ό ν™œμš©ν•œ private λ³€μˆ˜
function createCounter() {
    let count = 0;  // private λ³€μˆ˜ (μ™ΈλΆ€μ—μ„œ 직접 μ ‘κ·Ό λΆˆκ°€)

    return {
        increment() {
            count += 1;
            return count;
        },
        decrement() {
            count -= 1;
            return count;
        },
        getCount() {
            return count;
        }
    };
}

const counter = createCounter();
console.log(counter.increment());  // 1
console.log(counter.increment());  // 2
console.log(counter.getCount());   // 2
// counter.count;  // undefined (직접 μ ‘κ·Ό λΆˆκ°€)

πŸ—£ Practical Conversation Example

πŸ” Code Review: Variable Naming
πŸ‘¨β€πŸ’»
Senior Developer (Reviewer)
In this code you have let d = new Date() - startTime;, but it's hard to tell right away what d means. Could you change the variable name to something clearer?
πŸ‘©β€πŸ’»
Junior Developer
Ah, I calculated the elapsed time in milliseconds. Would changing it to const elapsedTimeMs = Date.now() - startTime; work? I changed it to const because this value isn't modified later.
πŸ‘¨β€πŸ’»
Senior Developer (Reviewer)
Good! It's nice that you included the unit (Ms) in the variable name. And the habit of declaring values that aren't reassigned with const is excellent too. One more thing: the let flag = true; below would be better with a meaningful name like isProcessing or shouldContinue.

πŸŽ“ Technical Interview: Explaining Hoisting
πŸ‘€
Interviewer
Please explain what hoisting is in JavaScript, and describe the difference in hoisting behavior between var and let.
πŸ‘©
Candidate
Hoisting refers to the behavior in which the JavaScript engine acts as if variable and function declarations are moved to the top of their scope before the code executes. The code isn't actually moved; during the compilation phase, only the declarations are registered in memory first.
πŸ‘©
Candidate
var is initialized to undefined when hoisted, so accessing it before its declaration gives undefined without an error. let and const, on the other hand, are hoisted but not initialized, so accessing them before their declaration causes a TDZ (Temporal Dead Zone) error. Because of this difference, let/const are safer, and these days we use let/const instead of var.
πŸ‘€
Interviewer
Good. Then have you ever had a bug caused by var in a real project?
πŸ‘©
Candidate
Yes, I had a problem when I used an index variable declared with var in a for loop inside a setTimeout callback. Only the value after the loop ended was printed, and it took time to find the cause, but changing it to let solved it right away. Since then I don't use var at all, and I have the no-var rule enabled in ESLint.

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠ Cautions

🚨 Practical Cautions for Variables
  • Do not use var: Since ES6, use only let and const. The function scope and hoisting behavior of var create bugs that are hard to predict. Enable ESLint's no-var rule.
  • Default to const: Use let only when reassignment is necessary, and use const otherwise. Maintaining immutability makes code easier to reason about.
  • Minimize global variables: Global variables can be modified from anywhere, making them hard to trace. Limit scope using module systems, closures, classes, and so on.
  • Use meaningful names: Instead of vague names like temp, data, and result, use specific names like userProfile and filteredProducts.
  • Declare and initialize together: If you initialize a variable later after declaring it, there is a period in which it exists in an undefined state. Initialize it at the same time as the declaration whenever possible.

πŸ”— Related Terms

πŸ“š Learn More