The let
keyword in JavaScript is like the old var
keyword in JavaScript except that it respects block scope. Before ES6, JavaScript only had function scope. Although there is nothing fundamentally wrong with function scope, it confuses a lot of people coming from C based languages which have block scope.
1) Block scope vs Function scope
Scope refers to some portion of the code where a variable exists. Outside of that scope the variable will be not be accessible or will be another variable with the same name.
a) Function scope
Function scope means that any variable defined anywhere inside a function, will be accessible anywhere in that function and will not exist outside of it.
b) Block scope
Block scope means that any variable defined anywhere inside any block (for example if
and for
blocks), will be accessible anywhere inside that block and will not exist outside of it.
2) JavaScript var
and let
In JavaScript, the var
keyword is function scoped. The let
keyword is block scoped.
a) Example
function main() { |
b) Notes
- Variables defined with
var
inside anif
block will exist inside the entire function they are defined in – ignoring theif
block. - Variables defined with
var
will exist and have a value of undefined in the section of the code before the initialisation. Check out variabled
in the example. The variable is created at the beginning of the function, this is called variable hoisting. - Variables defined with
let
will only exist within the block they are defined in. Trying to access the variable outside of the block will throw an Error. This is the case forc
in the example. - Use
let
to override the value of a function scoped variable inside a block only. Example:a
.
3) When to use let
a) In for
loops
Do
for(let i; i < n; i = i + 1) { |
instead of
var i; // Will be function scoped and can cause interferences |
b) In closures that need to retain creation time values
for(var i = 1; i < 4; i = i + 1) { |
Useful to create multiple instances of a variable inside a block.
c) For temporary variables inside blocks
var i = 0; |
4) let
caveats and warnings
a) No access to the variable before declaration
function main() { |
At first glance, the let
keyword does behave the same as var
when used in a function block. But if you try to access the variable before declaration you will get an error instead of an undefined
variable as you would with var
.
b) Double declarations are forbidden
if(condition) { |
c) Be careful when you feel like replacing a var
with let
Be careful when you feel like changing var
with let
. Usually that happens when a function should be split into several parts.
If your initial function looks like
function process(callback) { |
then suddenly looks like
function process(callback) { |
You should seriously consider rewriting your function as two functions:
function process1(callback) { |
Read more about why functions should only do one thing