Javascript let - what is it compared to var? and what is the difference between the two?

You might have started to see this keyword "let" from time to time. I stumbled upon this keyword looking through some code on github. I had never seen it before and wondered what it was. A replacement for var? or perhaps a better version? Var has been around since the start of javascript, whereas let is something new from ecma script 6.

The difference between let and var

You can read all the details on let here.

In order to tell what let is, we need to have a look at the similarities with var:

Var and let are a keywords used to assign values to a variable. They get values assigned to them by using the assignment operator =. It is possible to create a variable with no value at all which will be undefined. Both are hoisted within their scopes.

As you can see let and var are very alike. Their main function is to store and access values. But there are some differences:

In short let has block scope whereas var has function scope.

Variable scope is the main difference between var and let. Which is also the reason why let was created. In most programming languages variables have what is called block scope. Which means that a variable only is available within its block. A block is the code between curly braces - {}. This is the behavior for variables in most modern languages. Which is most likely the reason why let was created. Because what we had before let was var. Which does not work this way. Var has function scope. Which means that variables created are accessible within its function. If it is not created within a function, it will be available globally. Developers not used to javascript often mistake the var keyword for having block scope. Which can create some unwanted behavior. Below is an example:

function countToThree(){
  for(var i = 1; i <= 3; i++){
     let letI = i;
     var varI = i;
  //LetI does not exist in this scope, but varI does and is 3.
//varI does not exist in this scope.

the letI variable that we declare inside the for loop only exists within that block. However the varI exists outside the for loop block, but only inside the function.

Browser Support

  • Firefox: Available from release 44, which was released in Januar 2016.
  • Internet explorer: Supported from version 11.
  • Edge: Supported
  • Chrome: Supported in strict mode.
  • Safari: Not supported (Currently version 9)

The list for supported browsers can be found here.

That is all

I hope this helped you understand the differences between let and var better. Let me know what you think in the comments down below!