Still confused what makes different "var" of "let" declarator in javascript? Take a look !

What's the difference between LET and VAR in the declaration of variables in javascript

var and let are simple declarators that allows to declare a variable in a scope.

let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function.

But, what does that really means ? for example :

Let's suppose that we have 10 buttons with 10 different id but they follow the prefix "thebutton".

// Using VAR
for(var i=1; i<10; i++) {
    $("#thebutton" + i).click(function () { 
          alert(i); 
    });
}

The variable i will be taken in the scope of the click function in the button as a reference of i. That means, if you click any of the buttons, the value will be always 10.

'use strict'; 
// We need to set use strict, because all the Block-scoped declarations (let, const, function, class) are not yet supported outside strict mode

// Using let
for(let i=1; i<10; i++) {
    $("#thebutton" + i).click(function () { 
          alert(i); 
    });
}

Play a little bit with this example :

The history is another ! Every button will alert its number consecutively due to let instruction.

Really simple isn't ? let will be applied only in its block scope ! 

{ 
// Start block

// let will be useful here !

// End Block
}

If you do not finish to understand, let's try this another example :

'use strict';

var country = "russia";
var a = 5;
var b = 10;

if (country === "russia") {
  let a = 50; // A will be 50 only in russia !
  var b = 1; // Will be applied globally, B will be change in all the world !

  console.log(a);  // 50
  console.log(b);  // 1
}

// We are outside russia !!!

console.log(a); // a will be 5 again !
console.log(b); // 1

I hope this article has been helpful to understand the difference between these two statements.


Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Become a more social person

Sponsors