나무 숲

FE 기술면접 대비 / 호이스팅Hoisting 본문

Career/웹

FE 기술면접 대비 / 호이스팅Hoisting

wood.forest 2020. 11. 1. 18:26

호이스팅Hoisting?

ES6 이후에서 함수나 변수 선언이 해당 유효 범위(스코프)의 최상단으로 끌어올려지는 것처럼 보이는 현상.
실제로는, 컴파일 타임에 변수/함수 선언이 메모리에 들어가되 할당은 코드를 작성한 위치에서 진행된다.

 

특징

함수/변수 선언에만 적용된다.

초기화만 해주는 경우 Hoisting이 일어나지 않는다.

console.log(num); // Throws ReferenceError exception 
num = 6; // Initialization

함수 표현식은 정의된 함수를 변수에 할당하는 것이므로 Hoisting이 일어나지 않는다.

var square = function (x) {
  return x * x;
};

let, const 선언은 발생하지 않는다.

var로 변수를 선언한 경우에만 Hoisting이 일어난다.

 

Example1

Hoisting으로 인해, 함수 선언 전에 함수를 호출했음에도 정상 동작한다.
이는 JS에서 Context execution이 동작하는 방식 때문인데, 함수가 선언될 때 해당 함수의 참조와 함께 메모리에 저장된다.

catName("Chloe");

function catName(name) {
  console.log("My cat's name is " + name);
}

Example2

아래 두 코드는 사실 같다.

var scope = "global";
function f() {
  console.log(scope); //undefined
  var scope = "local";
  console.log(scope); //local
}
var scope = "global";
function f() {
  var scope;
  console.log(scope);
  scope = "local";
  console.log(scope);
}
  • f() 내에서 scope 변수가 선언되어 있으므로 hoisting이 발생한다.

 

Reference

https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
https://github.com/Febase/FeBase/blob/master/Javascript/Hoisting.md

728x90
반응형

'Career > ' 카테고리의 다른 글

Javascript TDD  (0) 2020.12.06
Javascript 공부 소스  (0) 2020.11.08
FE 기술면접 대비 / 브라우저가 웹서버로 요청을 보내는 과정  (0) 2020.10.15
눈으로 보는 JavaScript Event Loop  (0) 2020.08.29
웹 개발의 A-Z  (0) 2020.08.27
Comments