JavaScript

자바스크립트 Hoisting

CD2Y 2022. 9. 14.
반응형

See the Pen 자바스크립트 Hoisting by nilgi (@nilgi) on CodePen.

 

 

<h1>자바스크립트 Hoisting</h1>
<h3>Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).</h3>
<p id="js_h1"></p>
<script>
    x1 = 6;

    elem = document.getElementById("js_h1");
    elem.innerHTML = x1;

    var x;
</script>

<hr>

<p id="js_h2"></p>
<script>
    var x2;
    x2 = 87;

    elem = document.getElementById("js_h2");
    elem.innerHTML = x2;
</script>

<hr style="border-top: 5px solid;">

<p id="ih1"></p>
<script>
    var a = 1;
    var b = 9;

    elem = document.getElementById("ih1");
    elem.innerHTML = a + " " + b;
</script>

<hr>

<p id="ih2"></p>
<script>
    var a2 = 1;

    elem = document.getElementById("ih2");
    elem.innerHTML = a2 + " " + b2;

    var b2 = 9;
</script>

<hr>

<pre>
변수는 맨 위에 선언.
오류 방지를 위에 항상 시작 부분은 모든 변수를 선언한다.
자바스크립트의 기본 규칙입니다.
</pre>

 

반응형