Variables & scopes

In JavaScript is three type of variables var, letand const. Last two of those are new from ES6. Trend is saying to move away from var and use mostly the let variables. Here is still comparing of those three to understand the whole image.

Scopes in programming languages are controlling visibility and lifetime of variables. In JavaScript we have global, local and block level scope. Last of mentioned is new from ES6 and is used with let keyword.

var variables

Var uses global and local scopes. Local scopes are made with function declaration. Variable declared inside functions can only be used inside that function. This why local scope is also called as a function scope. Example of a local scope:

function scooper() {  
  var a = 1;
  console.log(a); // 1
}
scooper();

console.log(a); // Error. a is not defined here.  

If variables isn't declared inside a function, it's in global scope. Which means it's usable from anywhere in code. This is hazard idea and means that variables in global scope can be modified from inside functions.

Though if variable with same name is declared in both scopes, then is used shadowing. When calling a variable the used declaration is the nearest one. Here's an example:

var a = 0;

function scooper() {  
  var a = 1;
  console.log(a); // 1.
}
scooper();

console.log(a); // 0  

let variables

Keyword let declares block scope variable. This mean block statements which also includes functions. Here's difference example between var and let:

if (true) {  
  var a = 1;
  let b = 2;
}
console.log(a); // 1  
console.log(b); // error


function scoper() {  
  var c = 3;
  let d = 4;
}
scoper();  
console.log(c); // error  
console.log(d); // error

function looper() {  
  console.log(e); // undefined
  console.log(f); // error

  if (true) {
    var e = 5;
    let f = 6;
  }

  console.log(e); // 5
  console.log(f); // error
}
looper();  

As shown. let variable can't be seen outside of if block, but var can.

Another difference between var and let is global object. let, unlike var, does not create global object property.

var a = 1;  
let b = 2;  
console.log(this.a);  
console.log(this.b);  

const variables

Const variable is also block scope variable, like let. But unlike let, const variables can't be reassigned. That also means when you declare a const variable, you need also specify it's value.

Because value can't be reassigned, it's impossible to change value of example a string. But values inside array can be changed.