2021 프론트 엔드 로드맵 따라가기/JS
Variable Scope
알 수 없는 사용자
2021. 5. 30. 08:02
전역에 사용된 var가 함수 안과 if 나 loop 안에서 어떤 차이를 보이는지에 주목하자.
// Global Scope
var a = 1;
let b = 2;
const c = 3;
// function test() {
// var a = 4; // differ from global a
// var b = 5;
// var c = 6;
// console.log(`Function Scope: ${a} ${b} ${c}`);
// }
// test();
// Block Scope (if, loop, etc... wrapped in culry braces..)
// if(true) {
// var a = 4; // same as global a
// let b = 5;
// const c = 6;
// console.log(`If Scope: ${a} ${b} ${c}`);
// }
for(var a = 0; a < 10; a++) {
console.log(`Loop: ${a}`); // same as global a too
}
console.log(`Global Scope: ${a} ${b} ${c}`);