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

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 it's 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 it's functon. If it is not created within a function, it will be available globally. Developers not used to javascript often mistaske the var keyword for having block scope. Which can create some unwanted behavior.

Browser Support

  • Firefox: Will be available in release 44. Which should be released this month (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.