TDZ (Temporal Dead Zone) 이란?

hoo00nn·2020년 12월 29일
0
post-thumbnail

TDZ (Temporal Dead Zone) 이란 ?

변수의 선언과 변수의 초기화 사이의 변수에 접근할 수 없는 지점

즉, 초기화되지 않은 변수가 있는 곳을 Temporal Dead Zone이라고 한다.

몇 가지 문제를 제시하고 답을 설명하면서 이해를 돕겠다.

문제 1

let letValue = 'out Scope';

function hello() {
  console.log('letValue', letValue);
  let letValue = 'inner scope';
};

hello()

문제 2

let a = f(); 
const b = 2;
function f() { return b; }

문제 3

{  
	console.log(typeof nonsenseThatDoesntExist);
	console.log(typeof name); 

	let name = "hoo00nn";
}

설명

문제 1

답 : ReferenceError가 발생한다.

JS엔진은 코드를 수행하기 전 가장 먼저 코드에서 데이터를 위한 메모리를 설정한다. 이 과정을 호이스팅 이라 한다.

  1. JS엔진은 letValue변수와 hello 함수를 메모리에 등록한다. (GlobalContext의 Lexical Enviroment에 등록)
  2. letValue를 'out Scope'로 초기화한다.
  3. hello() 함수를 호출한다.
  4. hello() 함수를 호출하면 실행 컨텍스트가 만들어지고 letValue를 메모리에 등록 (helloContext의 Lexical Enviroment에 등록)
  5. console.log 실행 —> letValue는 메모리에 초기화 되지 않은 채로 등록되어 있기 때문에 ReferenceError 발생
let letValue = 'out Scope';

function hello() {
  // letValue가 TDZ에 영향을 받는 구간
  console.log('letValue', letValue); // ReferenceError
  let letValue = 'inner scope'; // letValue가 초기화 됨으로써, TDZ가 끝나게 됩니다.
};

hello()

여기서 한 가지 더 알아두면 좋은 개념을 설명하겠다.

let, const 변수가 실제로 할당되기 전에 실행만 되지 않는다면 참조는 할 수 있습니다. (eg. 함수 내)

function hello() {
  console.log('letValue', letValue);
};

let letValue = 'out Scope';
hello()

하지만 아래의 코드는 Reference error을 유발합니다.

function hello() {
  console.log('letValue', letValue);
};

hello(); // ReferenceError
let letValue = 'out Scope';

문제 2

답 : ReferenceError가 발생한다.

  1. 변수 a, b 와 함수 f()가 메모리에 등록된다.
  2. 메모리 등록이 완료된 후 1번째 라인을 실행시킨다.
  3. 함수 f()가 호출되고, f() 함수 내부에서 b를 리턴한다.
  4. 3번 과정에서 변수 b는 변수 선언만 되고 아직 초기화는 되지 않은 상태로 TDZ 지점에 있다. ReferenceError 발생
let a = f(); // 1
const b = 2;
function f() { return b; } // 2, b is in the TDZ

문제 3

답 : undefined 와 ReferenceError

  1. 첫 번째 console은 변수가 선언되지 않았기 때문에, typeof notDefined 는 undefined 로 평가한다.
  2. 그러나 TDZ의 변수에서 typeof 연산자를 사용하면 ReferenceError가 발생한다.
{
	console.log(typeof notDefined); 
	console.log(typeof name); // ReferenceError

	let name = "hoo00nn";
}

결론

TDZ는 const, let, class 구문의 유효성에 영향을 미치는 중요한 개념이다. TDZ는 선언 전에 변수를 사용하는 것을 허용하지 않는다.

profile
😀 신기술에 관심이 많고, 함께 성장하고 함께 개발하고 싶은 개발자가 되고 싶습니다. 😀

0개의 댓글