[javascript] Hoisting(호이스팅)

주영·2025년 1월 28일
0

Javascript

목록 보기
5/15

자바스크립트를 다루는 데에 있어서 아주 중요한 개념 중 하나인 Hoisting(호이스팅)에 대해서 다뤄보겠다.


Hoisting이란 무엇인가

함수, 변수 등의 선언을 위쪽으로 끌어올려 미리 선언하여 메모리 공간을 할당하는 것을 말한다.

함수

함수의 선언문은 hoisting되기에 함수 선언을 코드의 맨 아래에 두어도 정상적으로 작동하는 모습을 볼 수 있다.

  • 표현식에는 해당되지 않는다.
hello(); //hello!

function hello(){
  console.log("hello!");
}

변수

변수의 hoisting에서 유의해야 할 점이 몇 가지 있다.

  • 변수의 hoisting은 오로지 var 키워드에서만 일어난다는 점이다. letconst 키워드에서는 hoisting이 발생하지 않는다.
  • 변수의 선언만 hoisting이 되기 때문에 할당(초기화)는 적용되지 않는다.
console.log(a); //undefined
var a = 'A';
console.log(a); //A
console.log(a); //ReferenceError: Cannot access 'a' before initialization
let a = 'A';
console.log(a); //ReferenceError: Cannot access 'a' before initialization
const a = 'A';
profile
힘들어요

0개의 댓글