JavaScript

함수 선언문 vs 함수 표현식, 그리고 호이스팅

전개발 2023. 11. 23. 16:15
  • 함수 선언문은 함수 호이스팅이 일어난다.
  • 함수 표현식은 변수 호이스팅이 일어나지만, 함수 할당 전 사용이 불가하다.

 

 

 

다음은 가능하다.

  • 함수 선언문 hello가 함수호이스팅 되었기 때문이다.
function MyComponent () {
    hello() // hello

    function hello() {
        console.log("hello")
    }

    return <div/>
}

 

 

 

다음은 불가능하다

  • 함수 표현식을 저장하는 var 변수 hello는 최초 undefined로 초기화되며 변수 호이스팅된다.
  • 따라서 값 할당 전에는 함수로서 부를 수가 없다.
function MyComponent () {
    hello() // **not a function error**

    var hello = () => {
        console.log("hello")
    }

    return <div/>
}
  • 이때, var 대신 let 또는 const 를 사용한다면 다른 에러를 확인할 수 있다.
    • function MyComponent () {
      	hello() // **ReferenceError: Cannot access 'hello' before initialization**
      
      	const hello = () => {
      		console.log("hello")
      	}
      
      	return <div/>
      }
      ​
       
    • **ReferenceError: Cannot access 'hello' before initialization**
    • let과 const도 var과 마찬가지로 변수 선언을 끌어올려주는 호이스팅이 일어나지만
      • var는 undefined로 초기화 되는 반면,
      • let,const는 변수를 별도로 초기화 하지 않는다.
      • → 따라서 초기화 전에는 사용할 수 없다는 에러가 뜨는 것