Scope

  • 변수가 유효한 범위를 말합니다.
  • 어디까지 쓸 수 있는 지를 이야기하는 것입니다.
var x = 'global';

function foo () {
    var x = 'function scope';
    console.log(x); //function scope
}

foo();
console.log(x); //global
  • 스코프가 없다면 충돌하지 않도록 중복되는 변수명은 쓸 수 없을 것입니다.

1. Scope 종류

1.1. Global Scope

  • 코드 어디에서든지 참조할 수 있습니다.
  • var로 선언한 변수는 전역 객체에 속하게 됩니다.
    • client(브라우저)의 전역 객체는 window입니다.
    • Node.js에서는 global입니다.

1.2. Local Scope

  • JS가 다른 언어와 다른 점은 scope의 범위가 함수 블록 내입니다. ({}와 상관 없습니다)
if (true) {
  var x = 5;
}

console.log(x);  // 5
  • if문 안이지만 일반 블록이므로 x는 전역병수입니다.
(function () {
  var x = 5;
})();

console.log(x);  // Uncaught ReferenceError: x is not defined
  • let, const변수의 scope는 블록({}) 단위입니다.
{ 
    let x = 1; 
}

console.log(x); //Uncaught ReferenceError: x is not defined
  • 정리하면 var는 scope의 범위가 함수
  • let, const는 scope의 범위가 블록입니다.

2. Scope Chain

  • 변수가 해당 scope에서 유효하지 않을 때, 안에서부터 바깥으로만 차례로 검색해 나가는 것을 이야기합니다.
function sum() {

  var a = 3
    var b = 5;

  function inner() {
    var b = 7;
        var c = 11;

    a = a + b + c;    // a = 3, b = 7, c = 11
        console.log(a);  // 21

  };

    console.log(a);  // 3
  inner();
    console.log(a);  // 21
};

sum();
console.log(a); // Uncaught ReferenceError: a is not defined
Last modified: 2022년 02월 22일

Comments

Write a Reply or Comment

Your email address will not be published.