호이스팅

오늘은 호이스팅이라는 개념에 대해 정리해 보고자 한다. Modern JavaScript DeepDive에서 서술한 호이스팅에 관한 모든 것을 정리해봤다.

4.4 변수 선언의 실행 시점과 변수 호이스팅

12.4.3 함수 생성 시점과 함수 호이스팅

    // 함수 참조
    console.dir(add); // / add(x, y)
    console.dir(sub); // undefined
    // 함수 호출
    console.log(add(2, 5)); // 7
    console.log(sub(2, 5)); // TypeError: sub is not a function

    function add(x, y) {
    return x + y;
    }
    // 함수 표현식
    var sub = function (x, y) {
    return x - y;
    };

함수 호이스팅과 변수 호이스팅의 미묘한 차이?

15.1.3 var 키워드의 변수 호이스팅

15.2.3 let 키워드의 변수 호이스팅

   console.log(foo); // ReferenceError: foo is not defined
    let foo;
   let foo = 1; // 전역 변수
    {
    console.log(foo); // ReferenceError: Cannot access 'foo' before initialization
    let foo = 2; // 지역 변수
    }

25.3 클래스 호이스팅

   // 클래스 선언문
    class Person {}
    console.log(typeof Person); // function
   console.log(Person);
    // ReferenceError: Cannot access 'Person’ before initialization
    // 클래스 선언문
    class Person {}
   const Person = '';
    {
    // 호이스팅이 발생하지 않는다면 ’ '이 출력되어야 한다.
    console.log(Person);
    // ReferenceError: Cannot access 'Person' before initialization
    // 클래스 선언문
    class Person {}
    }

끝!