식별자가 유효한 범위
모든 식별자는 자신이 선언된 위치에 따라 스코프가 결정됨
식별자는 스코프 내에서 유일해야 하지만, 다른 스코프에는 같은 이름의 식별자가 존재할 수 있음 -> 스코프는 네임스페이스임
cf) 네임스페이스: 모든 식별자가 고유하도록 보장하는 코드 영역
// 전역 스코프
const x = "global x";
const y = "global y";
function outer() {
// outer 지역 스코프
const z = "outer's local z";
console.log(x); // global x
console.log(y); // global y
console.log(z); // outer's local z
function inner() {
// inner 지역 스코프
const x = "inner's local x";
console.log(x); // inner's local x
console.log(y); // global y
console.log(z); // outer's local z
}
inner();
}
outer();
console.log(x); // global x
console.log(z); // Uncaught ReferenceError: z is not defined
스코프가 계층적으로 연결된 것
var
키워드로 선언된 변수var x = 1;
if (true) {
var x = 2; // 전역변수 중복 선언
}
console.log(x); // 2
함수를 어디서 정의했는지에 따라 상위 스코프가 결정되는 것
const x = 1;
function foo() {
const x = 2;
bar();
}
function bar() {
console.log(x);
}
foo(); // 1
bar(); // 1