2023.10.26 - TIL

유니·2023년 10월 26일
0

Hoisting

Hoisting은 자바스크립트에서 발생하는 현상 중 하나로 변수와 함수를 선언하는 위치와 상관없이 해당스코프의 최상위로 끌어올려지는것을 말한다.

a();

function a(){
    console.log("a");
}
// 에러가 아닌 함수 a가 실행되는 모습을 볼 수 있다.

단, 값이 할당되는 과정이 아닌 선언되는 과정에서 호출되기때문에 값이 비어있는 모습을 볼 수 있다.

console.log(a); // undefined
var a = 1;
console.log(a); // 1

당연하게도 지역변수로 선언된 변수는 해당 지역안에서 최상위로 올라와지는것이지 전역에서 올라와지는것이 아니기때문에 에러가 발생한다.

a(); // a
console.log(b); // b is not defined;
function a(){
  	const b= 0;
    console.log("a");
}

ECMAScript 6 에서 추가된 let과 const는 변수 선언시 블록 스코프 변수이기때문에 var와는 다르게 undefined가 아닌 is not defined 에러가 발생한다.

console.log(b); // b is not defined
let b = 1;
console.log(b); // 1
profile
Prospective Junior Front-end Developer

0개의 댓글