JavaScript | TDZ

블로그 이사 완료·2022년 12월 26일
0
post-thumbnail

📍 Intro

TDZ(Temporal Dead Zone)를 해석하면 "일시적 사각지대"다.

첫 번째 코드 [인스턴스 생성 후 클래스 선언]

const myCat = new cat('mimi')

class cat {
  constructor(name) {
    this.name = name;
  }
}

두 번째 코드 [함수 호출 후 함수 선언]

hello('Shin')

function hello (name) {
  return `Hello ${name} :)`
}

위 두개의 코드를 실행해보면 두 번째 코드는 정상적으로 작동 하지만 첫 번째 코드를 작동시키면
ReferenceError: Cannot access 'cat' before initialization 에러가 발생한다.


📍 TDZ(Temporal Dead Zone)

const 변수를 선언하고, 초기화한 다음 변수 값을 출력하는 순서로 작동하는 코드

const cat = "야옹"

console.log(cat)

변수 값을 먼저 출력하고, 그 다음 선언 및 초기화 하는 코드

console.log(cat)

const cat = "야옹"

//error : ReferenceError

순서를 바꾸면 ReferenceError 오류가 나타나는 것을 볼 수 있다.

위 이미지를 참고하면 TDZ는 변수 선언 및 초기화 하기 전 사이의 사각지대라는 것을 알 수 있다.
즉, 변수를 선언 및 초기화 하기 전에 사용하면 TDZ에서 사용되는 변수이기 때문에 ReferenceError 에러가 나타나게 된다.


📍 TDZ의 영향을 받는 구문

#1. const 변수

// Bad
console.log(a)
const a = "a" //error : ReferenceError// Good
const a = "a"
console.log(a) // a

#2. let 변수

// Bad
count;

let count;

count = 10; //error : ReferenceError// Good
let count;

count; // undefined

count = 10;

count; // 10

#3. class문

// Bad
const myHome = new dog('coco')

class Dog{
  constructor(name){
    this.name = name;
  }
}

console.log(myHome.name) // error : ReferenceError// Good
class Dog{
  constructor(name){
    this.name = name;
  }
}
const myHome = new dog('coco')

console.log(myHome.name) // coco

#4. constructor() 안에 있는 super()

// Bad
class MuscleCar extends Car {
  constructor(color, power) {
    this.power = power;
    super(color);
  }
}
const myCar = new MuscleCar('blue', '300HP'); // error : ReferenceError// Good
class MuscleCar extends Car {
  constructor(color, power) {
    super(color);
    this.power = power;
  }
}
// Works!
const myCar = new MuscleCar('blue', '300HP');
myCar.power; // => '300HP'

#5. 기본 function의 매개변수

// Bad
const a = 2;
function square(a = a) {
  return a * a;
}

square(); // error : ReferenceError// Good
const init = 2;
function square(a = init) {
  return a * a;
}

square(); // 4

📍 TDZ의 영향을 받지 않는 구문

var / function / import statement

foo; // undefined
var foo;
hello('world') // 'Hello world'

function hello(text){
  return `Hello ${text}`;
}
hello('world') // 'Hello world'

결론, TDZ는 선언하기 전에 사용하는 것을 허용하지 않는다. TDZ에 영향을 미치는 const let class 를 사용할 때 항상 순서를 주의해서 사용해야 한다.
반대로 var 변수는 선언 전에도 사용할 수 있기 때문에(호이스팅) 에러 발생의 원인이 될 수 있기 때문에 var보다는 letconst 사용을 지향하자.

profile
https://kyledev.tistory.com/

0개의 댓글