JAVASCRIPT

호이스팅(Hoisting)

seo dori 2023. 11. 14. 09:57

JavaScript 호이스팅은 인터프리터가 코드를 실행하기 전에 함수, 변수, 클래스 또는 임포트(import)의 선언문을 해당 범위의 맨 위로 이동시키는 과정을 말합니다.

 

변수 스코프 (var는 블록문에 제한되지 않는다)

if (true) {
  var x = 5;
}
console.log(x); // 5

 

if (true) {
  let y = 5;
}
console.log(y); // ReferenceError: y is not defined

 

 

변수 호이스팅 (Hoisting)

나중에 선언된 변수를 참조할수 있다.즉 JavaScript 변수가 어떤 의미에서 함수나 문의 최상단으로 끌어올려지는 것을 말합니다. 하지만, 끌어올려진 변수는 undefined 값을 반환합니다. 그래서 심지어 이 변수를 사용 혹은 참조한 후에 선언 및 초기화하더라도, 여전히 undefined를 반환합니다.

/**
 * Example 1
 */
console.log(x === undefined); // true
var x = 3;

/**
 * Example 1--가 이루어 지는 방법
 */
var x;
console.log(x === undefined); // true
x = 3;

--------

/**
 * Example 2
 */
// undefined 값을 반환함.
var myvar = "my value";

(function () {
  console.log(myvar); // undefined
  var myvar = "local value";
})();

/**
 * Example 2
 */
// undefined 값을 반환함.
var myvar = "my value";

(function () {
  var myvar
  console.log(myvar); // undefined
  myvar = "local value";
})();

 

 

이러한 이유때문에 var는 최상단에서 선언하는게 좋다.

 

함수 호이스팅

함수에서 함수 선언은 호이스팅 되지만 함수 표현식으로는 호이스팅되지 않습니다.

/* 함수 선언 */

foo(); // "bar"

function foo() {
  console.log("bar");
}

/* 함수 표현식 */

baz(); // TypeError: baz is not a function

var baz = function () {
  console.log("bar2");
};

arrowFunction();  // TypeError: baz is not a function

const arrowFunction = () => {
  console.log("bar3");
};

 

 

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Grammar_and_types#variable_hoisting