Skip to main content

The Problems of Global Variable, “let, const” keyword and block level scope

The Problems of Global variable

global variablelocal variable
operation(or running)run without explicit callexists after function runs
scopeglobal scopelexical scope(function)
Lifecyclesame as lifecycle of global objectalive until lexical scope removed
ProblemsImplicit combinations

(all codes can reference and change global variables)

Long lifecycles (and therefore memory resources are also consumed as time goes by)

Presence at endpoints on the scope chain (the slowest search for global variables)

Namespace contamination (variable name conflict) | 스코프는 항상 좁은게 낫다 따라서 전역변수보다 권장된다. scope would be alway better to be narrow so it is prefered compared to global scope |

How to surpress global variable

  • immediately-invoked function: all codes wrapped with bracket(”(”) ⇒ all variables are local variable of immediately-invoked function
  • Namespace variable
var MYAPP = { name: "KIM" }
  • ES6 module

    • ES6 module provide independent module scope of file itself
      • variable with var keyword is not global variable, and not window
    // if adding  type="module"
    // javascript file run as module
    <script type="module" src="lib.mjs"></script>

let, const keyword and block level scope

problem of variable declared as var keyword

  • “duplicate declaration” enabled
var x = 1;
var y = 1;

// var 키워드로 선언된 변수는 같은 스코프 내에서 중복 선언을 허용// 초기화문이 있는 변수 선언문은 자바스크립트 엔진에 의해 var 키워드가 없는 것처럼 동작var x = 100

// 초기화 문이 없는 변수 선언문은 무시됨var y

console.log(x); // 100console.log(y)// 1
  • function-level scope

오직 함수 스코프만 지역스코프로 인정

블록스코프는 무시

var i = 10;

// for문에서 선언한 i는 전역 변수다.// 이미 선언된 전역변수가 i가 있으므로 중복선언됨for (var i = 0; i <5; i++) {
console.log(i);// 0 1 2 3 4
}

console.log(i);// 5
  • 변수 호이스팅
// 에러는 발생안됨console.log(foo)// undefined// 변수에 값을 할당(3. 할당 단계)
foo = 123;

console.log(foo); // 123// 변수 선언은 런타임 이전에 자바스크립트 엔진에 의해 암묵적 실행됨var foo;