JavaScript

자바스크립트에서 let, const로 선언한 변수들이 window 객체에 없는 이유?

milliwonkim 2023. 3. 9. 19:44
반응형
SMALL
let과 const 키워드로 선언된 변수는 전역 객체의 프로퍼티로 등록되지 않습니다.
따라서, 이들 변수는 window 객체에서 찾을 수 없습니다.
예를 들어, 다음과 같이 let 키워드로 선언된 변수 myVariable을 사용할 때

 

window.myVariable을 출력해보면 undefined이 반환됩니다.
let myVariable = 42;

console.log(window.myVariable); // undefined
 
마찬가지로, const 키워드로 선언된 변수 myConstant를 사용할 때도 
window.myConstant를 출력하면 undefined이 반환됩니다.

 

const myConstant = "Hello, world!";

console.log(window.myConstant); // undefined

 

따라서, let과 const 키워드로 선언된 변수는 전역 객체에서 찾을 수 없습니다.
이들 변수는 지역 범위에서 선언되며, 해당 지역 범위에서만 사용할 수 있습니다. 
 
하지만 var로 선언할 경우, window에서 확인할 수 있습니다.
var myConstant = "Hello, world!";

console.log(window.myConstant); // "Hello, world"
반응형
LIST