[Javascript] Hoisting

프레첼·2023년 3월 17일
0

Javascript

목록 보기
1/1
post-thumbnail

Hoisting

  • 변수가 선언된 시점보다 앞에서 사용되는 현상.
  • 함수는 생성 단계에서 전체가 저장되므로 호출 가능.

    var

    • var는 생성 단계에서 undefined로 초기화(initialization);
     console.log(someFunc());
     // undefined
    
     var x =10;
    
     console.log(someFunc()); // 10
    
    function someFunc(){
         return x; 
     }

    const, let

    • const, let 변수는 생성 단계에서 초기화되지 않는다.
     // ReferenceError : Cannot access 'a'a
     // before initialization
     console.log(someFunc());
    
     let x = 10
     
     console.log(someFunc()); // 10
    
    function someFunc(){
        return x;
    } 

TDZ (Temporal Dead Zone)

  • 선언문 이전에 접근 시 ReferenceError
  • 빨간 박스가 TDZ 구역이다.
  • 따라서 let, const는 hoisting이 발생하지 않는다.
profile
흐르는 대로 설명하기 && 틀리면 훈수 둬 주세요... 😊

0개의 댓글