JavaScript의 변수의 스코프(Scope)

BossTeemo·2024년 5월 4일
post-thumbnail

JavaScript에서의 변수의 스코프(Scope)

소개

JavaScript에서 스코프는 변수의 가시성과 수명을 정의하는 중요한 개념입니다. 스코프는 코드의 어느 부분에서 특정 변수를 사용할 수 있는지를 결정합니다. 스코프를 제대로 이해하면 코드의 가독성과 유지보수성을 높일 수 있습니다.

스코프의 종류

  1. 전역 스코프 (Global Scope)

    • 전역 스코프의 변수는 프로그램 전체에서 접근 가능합니다. 함수 밖에서 선언된 변수는 전역 변수가 됩니다.
    let globalVar = 'I am global';
    
    function showGlobal() {
        console.log(globalVar); // I am global
    }
    
    showGlobal();
  2. 함수 스코프 (Function Scope)

    • var 키워드로 선언된 변수는 함수 스코프를 가집니다. 함수 내에서 선언된 변수는 함수 내부에서만 접근할 수 있습니다.
    function example() {
        var localVar = 'I am local';
        console.log(localVar); // I am local
    }
    
    example();
    console.log(localVar); // ReferenceError: localVar is not defined
  3. 블록 스코프 (Block Scope)

    • ES6에서 도입된 letconst 키워드는 블록 스코프를 가집니다. 중괄호 {}로 둘러싸인 블록 내에서 선언된 변수는 해당 블록 내부에서만 접근할 수 있습니다.
    if (true) {
        let blockVar = 'I am in a block';
        const constVar = 'I am constant in a block';
        console.log(blockVar); // I am in a block
        console.log(constVar); // I am constant in a block
    }
    
    console.log(blockVar); // ReferenceError: blockVar is not defined
    console.log(constVar); // ReferenceError: constVar is not defined

중첩 스코프 (Nested Scope)

스코프는 중첩될 수 있으며, 내부 스코프에서는 외부 스코프의 변수에 접근할 수 있지만, 그 반대는 불가능합니다.

let outerVar = 'Outer';

function outerFunction() {
    let innerVar = 'Inner';

    function innerFunction() {
        console.log(outerVar); // Outer
        console.log(innerVar); // Inner
    }

    innerFunction();
}

outerFunction();
console.log(innerVar); // ReferenceError: innerVar is not defined

클로저 (Closure)

클로저는 내부 함수가 외부 함수의 변수에 접근할 수 있는 기능을 말합니다. 내부 함수가 외부 함수의 변수를 계속 참조할 수 있습니다.

function outer() {
    let outerVar = 'Outer Variable';

    return function inner() {
        console.log(outerVar);
    };
}

let innerFunc = outer();
innerFunc(); // Outer Variable

결론

JavaScript에서의 스코프는 변수가 어디에서 접근 가능한지 결정합니다. 전역 스코프, 함수 스코프, 블록 스코프를 이해하고 적절히 활용하여 코드를 더욱 효율적으로 작성하세요.

profile
1인개발자가 되겠다

0개의 댓글