TIL_78_호이스팅

JIEUN·2021년 5월 4일
0
post-thumbnail

Hoisting??????????

호이스팅이란, 함수 또는 변수의 선언을 각각의 유효 범위의 최상단에 선언해주는 것을 말한다.

  • 유효범위란? 함수 블록 {} 을 말한다.
  • JS Parser가 유효 범위 내의 코드를 훑은 후, 이를 기억했다가 실행시킨다.
  • 함수와 변수의 선언과 초기화를 분리하는 과정이라고 생각할 수 있다.
  • 메모리 관점으로 보았을 때, 컴파일 단계에서의 위치와는 다르지 않다.
    즉, 코드가 옮겨지는 것은 아니다.

변수 호이스팅

num = 6;
num + 7;
var num;
// num 이 선언되지 않더라도 에러를 내지 않는다.

위의 코드를 실행했을 때 undefined가 출력될 것 같지만, 13이라는 결과가 출력된다.

// After Hoisting
var num;
num = 6;
num + 7;

그 이유는 호이스팅 때문이다. 호이스팅 과정에서 JS Parser가 기억해두고 실행시킨다고 언급했듯이 var num; (선언부)를 유효 범위의 최상부로 끌어올려 실행시키기 때문에 에러가 생기지 않는다.

에러케이스를 봐보자.

var x = 1; // x 초기화
console.log( x + "" + y ); // 1undefined
var y = 2;

1undefined 가 출력된다.

// After Hoisting
var x = 1; // x 초기화
var y; // y 선언
console.log( x + "" + y ); // 1undefined
y = 2; // y 초기화

그 이유는 변수의 선언부만 Hoist 되기 때문에, console.log를 실행하는 단계에서는 변수 y가 초기화 되지 않았기 때문이다.

함수 호이스팅

catName("Chloe");

function catName(name) {
  console.log("My cat's name is " + name);
}
// 결과는 "My cat's name is Chloe"

"My cat's name is Chloe" 가 출력.

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

catName("Chloe");
// 결과는 "My cat's name is Chloe"

함수 또한 변수처럼 선언부가 호이스팅 되면 위와 같이 코드가 실행되기 때문에 에러없이 정상으로 결과가 출력된다.

Error 케이스를 봐보자.

catName("Chloe");

var catName = function(name) {
  console.log("My cat's name is " + name);
}
// TypeError: catName is not a function

이유는, 선언부만 최상부로 끌고 가기 때문에, 초기화되지 않은 catName("Chloe")는 에러가 난다.

Hoisting 우선순위.

변수와 함수가 같은 이름으로 선언될 경우, 우선순위는 변수에 있게 된다.

var fruit = "Apple";

function fruit() {
  console.log("Pear");
}
function vegetable() {
  console.log("Onion");
}

var vegetable = "Potato";

console.log(typeof fruit); // 'string'
console.log(typeof vegetable); // 'string'

fruit의 타입은 string, vegetable의 타입은 function일 것 같지만,
둘 다 string이 출력.

var fruit = "Apple";
var vegetable;

function fruit() {
  console.log("Pear");
 }
function vegetable() {
  console.log("vegetable");
}

vegetable = "Potato";

console.log(typeof fruit); // 'string'
console.log(typeof vegetable); // 'string'

호이스팅을 할 때, 변수가 함수보다 우선순위에 있기 때문에 vegetable의 선언부가 위로 올라간다. 그 후, vegetable() 함수가 초기화되지만, 다시 vegetable = "Potato"; 가 다음 라인에서 다시 초기화가 된다. 따라서, 콘솔에서 fruit, vegetable 모두 string 타입이 출력된다.

0개의 댓글