Video
Overview
There are three main differences when declaring a variable with let
vs var
.
let | var | |
---|---|---|
Scope | block scoped | function scoped |
Can Redeclare | No | Yes |
Hoisting | No | Yes |
Scope
Global Scope
Variables declared Globally (outside any function or block) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var
and let
behave quite similarly when declared in this context.
Function Scope
Similarly, variables defined with both var
and let
inside a Function are scoped to that function and are not accessible outside the Function Scope but can be accessed from any sub-scope.
Block Scope
The difference comes when variables are defined within a Block. Variables declared inside a { }
block with let
cannot be accessed outside the block scope, whereas variables defined with var
can.
Can Redeclare
A variable declared with var
can be redeclared over and over again. A variable declared with let
cannot be redeclared within the same scope and will throw an error.
Redeclaring a variable with var
in a different scope or block also changes the value of the outer variable. This behaviour can produce some of the most challenging errors to debug.
Redeclaring a variable with let
in a different scope or block treats that variable as a different new variable. And the value of the variable outside does not change.
Hoisting
Unlike languages like C, variables and functions in JavaScript are not declared at the point of use.
Instead, no matter where they are declared, variables defined with the var
keyword are moved to the top of their scope and assigned a default value of undefined
until they're reached in code.
Variables defined with let do not allow hoisting and will throw an error if accessed before the declaration.
console.log(a);
let a; // Uncaught ReferenceError: a is not defined
If you want to learn more about hoisting, take a look at my variable-and-function-hoisting article.
Conclusion
The let
keyword was introduced in the later version of JavaScript known as ES6(ES2015). And due to its straightforward approach to scope and ability to produce more readable and maintainable code, let
is the preferred way to declare variables.