What is scope?
스코프(scope)는 변수 접근성(variable accessibility)을 결정한다. 자바스크립트에는 세 가지 스코프가 존재한다.
- Block scope
- Function scope
- Global scope
블락 스코프는 자바스크립트 ES6 (2015) 부터 let
과 const
키워드를 제공하면서 생겨났다. 따라서 var
은 블락 스코프를 가질 수 없다는 점을 주의해야 한다. 예시를 통해 조금 더 자세히 알아보자.
Global scope
함수 바깥에서 정의된 변수는 글로벌 스코프를 가지게 된다. 따라서 자바스크립트 프로그램 내부 어디에서든 접근이 가능하다. 또한 글로벌 스코프에서는 let
, const
, var
로 선언된 변수들이 거의 비슷하게 동작한다.
let a = 10;
function foo() {
console.log(a);
}
foo(); // 10 출력
Function scope
함수 내부에서 정의된 변수는 함수 스코프를 가지게 된다. 따라서 함수 바깥에서는 이 변수에 접근할 수 없다.
function bar() {
let b = 20;
console.log(b);
}
bar(); // 20 출력
console.log(b); // Uncaught ReferenceError: b is not defined
var
로 선언된 변수 또한 함수 스코프를 가질 수 있으므로 위의 예시에서 let
을 var
로 바꾸어도 결과는 동일하다. 그러나 var
은 블락 스코프를 가질 수 없기 때문에 다음과 같은 이상한(?) 문제가 발생한다.
{
var c = 30;
}
console.log(c); // 30 출력
상위 스코프는 하위 스코프의 변수에 접근할 수 없어야 하는데, 위와 같이 글로벌 스코프에서 { }
안에서 선언된 변수에 접근할 수 있는 것을 확인할 수 있다. 이러한 문제를 해결하기 위해 자바스크립트 ES6부터 let
과 const
키워드를 제공한다. let
과 const
키워드로 선언한 변수는 블락 스코프를 가질 수 있다.
Block scope
{ }
안에서 선언된 변수는 블락 스코프를 가진다. 위에서도 언급했듯이, var
로 선언된 변수는 블락 스코프를 가질 수 없음을 주의해야 한다.
{
let d = 40;
}
console.log(d); // Uncaught ReferenceError: d is not defined
Lexical Scoping
Lexical scoping describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope. (MDN)
렉시컬 스코핑은 어디서 변수에 접근할 수 있는지를 결정할 때 소스코드 내에서 그 변수가 선언된 장소를 사용한다는 것을 의미한다. 따라서 함수 안에 포함된 함수는 상위 스코프(상위 함수)에서 선언된 변수에 접근할 수 있다. 반대로 상위 스코프에서는 하위 스코프에서 선언된 변수에 접근할 수 없다.
function outer() {
console.log(y);
function inner() {
let y = "hello";
console.log(x);
}
inner();
}
outer(); // Uncaught ReferenceError: y is not defined
function outer() {
let x = "hello";
function inner() {
console.log(x);
}
inner();
}
outer(); // hello 출력
Reference
'Javascript Concepts' 카테고리의 다른 글
RequestAnimationFrame (0) | 2021.10.13 |
---|---|
Message Queue and Event Loop (0) | 2021.10.05 |
IIFE (0) | 2021.10.01 |
ES Modules (0) | 2021.09.27 |