Scope

There are two types of scope in JavaScript.

  • global scope - anything declared outside of function
  • local scope - everything that declared inside function
  • module scope - since ES6, everything that declared inside module

JavaScript does not support block level scope inside { }.

x = 1; // global variable
var y = 2; // global

// a and b local variables
function myFunc(a){
    var b = a + 34; 
}

if(true) { // no new scope
  var z = 3;
}

alert(z); // worked, z visible 
 

Global scope

Everything declared outside of function placed to global scope. A variable declared without a var statement is also a global variable.

Local scope

Everything declared inside function. Function parameters are considered as local variables.