13. Hoisting (JS style guide)

코비코 koreanvisionarycoder ㅣ 2023. 1. 27. 11:02

 

var, const/let 선언의 호이스팅:


var declarations get hoisted to the top of their scope, their assignment does not. const and let declarations are blessed with a new concept called Temporal Dead Zones (TDZ). It's important to know why typeof is no longer safe.

  • var
    • 선언문은 가장 가까운 함수 스코프의 최상단으로 호이스팅 된다.
    • 할당문은 호이스팅 되지 않는다.
  • const/let
    • 선언에는 Temporal Dead Zones (TDZ) 가 존재한다.
    • typeof 는 안전하지 않다. (예시 참고)

 

// 아래 함수는 참조 에러를 일으킨다 (notDefined 라는 전역 변수가 존재하지 않을 때)
function example() {
  console.log(notDefined); // => throws a ReferenceError
}

// declaredButNotAssigned 는 호이스팅이 일어나기 때문에 사용가능하다.
// Note: 하지만 true 할당은 호이스팅 되지 않음.
function example() {
  console.log(declaredButNotAssigned); // => undefined
  var declaredButNotAssigned = true;
}

// 인터프리터는 변수의 선언을 스코프의 최상단으로 호이스팅 한다.
function example() {
  let declaredButNotAssigned;
  console.log(declaredButNotAssigned); // => undefined
  declaredButNotAssigned = true;
}

// const / let 의 예시
function example() {
  console.log(declaredButNotAssigned); // => throws a ReferenceError
  console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
  const declaredButNotAssigned = true;
}

 

 

익명함수 표현식의 호이스팅 : 변수 이름 O, 함수할당 X


 Anonymous function expressions hoist their variable name, but not the function assignment.

무명함수의 경우 함수가 할당되기 전의 변수가 hoist 됩니다.

function example() {
  console.log(anonymous); // => undefined

  anonymous(); // => TypeError anonymous is not a function

  var anonymous = function () {
    console.log('anonymous function expression');
  };
}

 

 

이름있는 함수 표현식의 호이스팅: 변수이름 O, 함수이름과 body X


Named function expressions hoist the variable name, not the function name or the function body.

명명함수의 경우도 똑같이 변수가 hoist 됩니다. 함수명이나 함수본체는 hoist 되지 않습니다.

function example() {
  console.log(named); // => undefined

  named(); // => TypeError named is not a function

  superPower(); // => ReferenceError superPower is not defined

  var named = function superPower() {
    console.log('Flying');
  };
}

// the same is true when the function name
// is the same as the variable name.
// 함수명과 변수명이 같은 경우도 같은 현상이 발생합니다.
function example() {
  console.log(named); // => undefined

  named(); // => TypeError named is not a function

  var named = function named() {
    console.log('named');
  }
}

 

함수 선언문의 호이스팅: 함수 이름, body O


Function declarations hoist their name and the function body.

함수선언은 함수명과 함수본체가 hoist 됩니다.

function example() {
  superPower(); // => Flying

  function superPower() {
    console.log('Flying');
  }
}