코딩공부/HTML,CSS,JavaScript

JavaScript_hoisting

diary100 2023. 4. 11. 18:02

호이스팅(hoisting)

-인터프리터가 변수와 함수의 메모리 공간을 선언 전에 미리 할당하는 것
- var로 선언한 변수의 경우 호이스팅 시 undefined로 변수를 초기화
- let 과 const로 선언한 변수의 경우 호이스팅 시 변수를 초기화하지 않음

 

✔변수타입으로 함수를 설정한다면 호이스팅이 일어나면서 해당하는 변수를 초기화 하면서 함수는 끌어올려지지 않으므로 오류가난다.

 

HTML 예제 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>호이스팅</title>
</head>
<body>
    <h2>호이스팅</h2>
    <script>
        func1();             // 이건 가능
        func2();             // 이건안됨 , 변수타입으로 함수를 설정한다면 호이스팅이 일어나면서 해당하는 변수를 초기화 하면서 함수는 끌어올려지지 않으므로 오류가난다.
        function func1(){
            alert('func1 호출');
        }
        const func2 = function(){
            alert('func2 호출');
        }
        func1();
        func2();
    </script>
</body>
</html>

결과