I'm wondering what is the difference between let and const in ES6. Both of them are block scoped, as the example in the following code:
const PI = 3.14;
console.log(PI);
PI = 3;
console.log(PI);
const PI = 4;
console.log(PI);
var PI = 5;
console.log(PI);
In ES5 the output will be:
3.14
3.14
3.14
3.14
But in ES6 it will be:
3.14
3
4
5
I'm wondering why ES6 allows the change of const value, the question is why should we use 'const' now? we can use 'let' instead?
Note: jsbin can be used for testing, choose JavaScript to run ES5 code and Traceur to run it with ES6 capabilities.
The difference between let and const is that once you bind a value/object to a variable using const, you can't reassign to that variable. In other words Example:
const something = {};
something = 10; // Error.
let somethingElse = {};
somethingElse = 1000; // This is fine.
The question details claim that this is a change from ES5 — this is actually a misunderstanding. Using const in a browser that only supports ECMAScript 5 will always throw an error. The const statement did not exist in ECMAScript 5. The behaviour in is either JS Bin being misleading as to what type of JavaScript is being run, or it’s a browser bug.
In practice, browsers didn't just go from 0% support for ECMAScript 2015 (ECMAScript 6) to 100% in one go — features are added bit-by-bit until the browser is fully compliant. What JS Bin calls ‘JavaScript’ just means whatever ECMAScript features your browser currently supports — it doesn’t mean ‘ES5’ or ‘ES6’ or anything else. Many browsers supported const and let before they fully supported ES6, but some (like Firefox) treated const like let for some time. It is likely that the question asker’s browser supported let and const but did not implement them correctly.
Secondly, tools like Babel and Traceur do not make ES6 ‘run’ in an older browser — they instead turn ES6 code into ES5 that does approximately the same thing. Traceur is likely turning const statements into var statements, but I doubt it is always enforcing that the semantics of a const statement are exactly replicated in ES5. Using JS Bin to run ES6 using Traceur is not going to give exactly the same results as running ES6 in a fully ES6 specification-compliant browser.
It is important to note that const does not make a value or object immutable.
const myArray = [];
myArray.push(1); // Works fine.
myArray[1] = 2; // Also works fine.
console.log(myArray); // [1, 2]
myArray = [1, 2, 3] // This will throw.
Probably the best way to make an object (shallowly) immutable at the moment is to use Object.freeze() on it. However, this only makes the object itself read-only; the values of the object’s properties can still be mutated.
What you're seeing is just an implementation mistake. According to the ES6 spec wiki on const, const is:
A initialize-once, read-only thereafter binding form is useful and has
precedent in existing implementations, in the form of const
declarations.
It's meant to be read-only, just like it currently is. The ES6 implementation of const in Traceur and Continuum are buggy (they probably just overlooked it)
Here's a Github issue regarding Traceur not implementing const
let
Use block scope in programming.
for every block let create its own new scope which you cannot access in outside of that block.
value can be changed as many times as you want.
let is extremely useful to have for the vast majority of code. It can greatly enhance your code readability and decrease the chance of a programming error.
let abc = 0;
if(true)
abc = 5 //fine
if(true){
let def = 5
}
console.log(def)
const
It allows you to be immutable with variables.
const is a good practice for both readability and maintainability and avoids using magic literals e.g.
// Low readability
if (x > 10) {
}
//Better!
const maxRows = 10;
if (x > maxRows) {
}
const declarations must be initialized
const foo; // ERROR: const declarations must be initialized
A const is block scoped like we saw with let:+
const foo = 123;
if (true) {
const foo = 456; // Allowed as its a new variable limited to this `if` block
}
The let and const
ES6 let allows you to declare a variable that is limited in scope to the block (Local variable). The main difference is that the scope of a var variable is the entire enclosing function:
if (true) {
var foo = 42; // scope globally
}
console.log(foo); // 42
The let Scope
if (true) {
let foo = 42; // scoped in block
}
console.log(foo); // ReferenceError: foo is not defined
Using var in function scope is the same as using let:
function bar() {
var foo = 42; // scoped in function
}
console.log(foo); // ReferenceError: foo is not defined
The let keyword attaches the variable declaration to the scope of whatever block it is contained in.
Declaration Order
Another difference between let and var is the declaration/initialization order. Accessing a variable declared by let earlier than its declaration causes a ReferenceError.
console.log(a); // undefined
console.log(b); // ReferenceError: b is not defined
var a = 1;
let b = 2;
Using const
On the other hand, using ES6 const is much like using the let, but once a value is assigned, it cannot be changed. Use const as an immutable value to prevent the variable from accidentally re-assigned:
const num = 42;
try {
num = 99;
} catch(err) {
console.log(err);
// TypeError: invalid assignment to const `number'
}
num; // 42
Use const to assign variables that are constant in real life (e.g. freezing temperature). JavaScript const is not about making unchangeable values, it has nothing to do with the value, const is to prevent re-assigning another value to the variable and make the variable as read-only. However, values can be always changed:
const arr = [0, 1, 2];
arr[3] = 3; // [0, 1, 2, 3]
To prevent value change, use Object.freeze():
let arr = Object.freeze([0, 1, 2]);
arr[0] = 5;
arr; // [0, 1, 2]
Using let With For Loop
A particular case where let is really shines, is in the header of for loop:
for (let i = 0; i <= 5; i++) {
console.log(i);
}
// 0 1 2 3 4 5
console.log(i); // ReferenceError, great! i is not global
Summary:
Both the let and the const keyword are ways to declare block scoped variables. There is one big difference though:
Variables declared with let can be reassigned.
Variables declared with const have to be initialized when declared and can't be reassigned.
If you try to reassign variables with declared with the const keyword you will get the following error (chrome devtools):
Why should we use this?
If we know that we want to assign a variable once and that we don't want to reassign the variable, using the const keywords offers the following advantages:
We communicate in our code that we don't want to reassign the variable. This way if other programmmers look to your code (or even you to your own code you wrote a while ago) you know that the variables which are declared with const should not be reassigned. This way our code becomes more declarative and easier to work with.
We force the principle of not being able to reassign a variable (JS engine throws error). This way if you accidentally try to reassign a variable which is not meant to be reassigned you can detect this at an earlier stage (because it's logged to the console).
Caveat:
Although a variable declared with const can't be reassigned this doesn't mean that an assigned object isn't mutable. For example:
const obj = {prop1: 1}
// we can still mutate the object assigned to the
// variable declared with the const keyword
obj.prop1 = 10;
obj.prop2 = 2;
console.log(obj);
If you also want your object to be non mutable you can use Object.freeze() in order to achieve this.
let and const
Variables declared with let and const eliminate specific issue of hoisting because they’re scoped to the block, not to the function.
If a variable is declared using let or const inside a block of code (denoted by curly braces { }), then the variable is stuck in what is known as the temporal dead zone until the variable’s declaration is processed. This behavior prevents variables from being accessed only until after they’ve been declared.
Rules for using let and const
let and const also have some other interesting properties.
Variables declared with let can be reassigned, but can’t be
redeclared in the same scope.
Variables declared with const must be assigned an initial value, but
can’t be redeclared in the same scope, and can’t be reassigned.
Use cases
The big question is when should you use let and const? The general rule of thumb is as follows:
use let when you plan to reassign new values to a variable, and
use const when you don’t plan on reassigning new values to a
variable.
Since const is the strictest way to declare a variable, it is suggest that you always declare variables with const because it'll make your code easier to reason about since you know the identifiers won't change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.
var declarations are globally scoped or function scoped while let and
const are block scoped.
var variables can be updated and re-declared within its scope; let
variables can be updated but not re-declared;const variables can neither be updated nor re-declared.
They are all hoisted to the top of their scope. But while var
variables are initialized with undefined, let and const variables are
not initialized.
While var and let can be declared without being initialized, const
must be initialized during declaration.
Here are some notes that I took that helped me on this subject. Also comparing const and let to var.
Here's about var:
// Var
// 1. var is hoisted to the top of the function, regardless of block
// 2. var can be defined as last line and will be hoisted to top of code block
// 3. for undefined var //output error is 'undefined' and code continues executing
// 4. trying to execute function with undefined variable
// Example: // log(myName); // output: ReferenceError: myName is not defined and code stops executing
Here's about let and const:
// Let and Const
// 1. use `const` to declare variables which won't change
// 2. `const` is used to initialize-once, read-only thereafter
// 3. use `let` to declare variables which will change
// 4. `let` or `const` are scoped to the "block", not the function
// 5. trying to change value of const and then console.logging result will give error
// const ANSWER = 42;
// ANSWER = 3.14159;
// console.log(ANSWER);
// Error statement will be "TypeError: Assignment to constant variable." and code will stop executing
// 6. `let` won't allow reference before definition
// function letTest2 () {
// log(b);
// let b = 3;}
// Error statement will be "ReferenceError: b is not defined." and code will stop executing
Var
The var keyword was introduced with JavaScript.
It has global scope.
It can be declared globally and can be accessed globally.
Variable declared with var keyword can be re-declared and updated in the same scope.
Example:
function varGreeter(){
var a = 10;
var a = 20; //a is replaced
console.log(a);
}
varGreeter();
It is hoisted.
Example:
{
console.log(c); // undefined.
//Due to hoisting
var c = 2;
}
Let
The let keyword was added in ES6 (ES 2015) version of JavaScript.
It is limited to block scope.
It can be declared globally but cannot be accessed globally.
Variable declared with let keyword can be updated but not re-declared.
Example:
function varGreeter(){
let a = 10;
let a = 20; //SyntaxError:
//Identifier 'a' has already been declared
console.log(a);
}
varGreeter();
It is not hoisted.
Example:
{
console.log(b); // ReferenceError:
//b is not defined
let b = 3;
}
Global object property
var no1 = "123"; // globally scoped
let no2 = "789"; // globally scoped
console.log(window.no1); // 123
console.log(window.no2); // undefined
Redeclaration:
'use strict';
var name= "Keshav";
var name= "Keshav Gera"; // No problem, 'name' is replaced.
let surname= "Rahul Kumar";
let surname= "Rahul Khan "; // SyntaxError: Identifier 'surname' has already been declared
Hoisting
function run() {
console.log(name); // undefined
var name= "Keshav";
console.log(name); // Keshav
}
run();
function checkHoisting() {
console.log(name); // ReferenceError
let name= "Keshav";
console.log(name); // Keshav
}
checkHoisting();
Note: in case of var, you will get undefined, in case of let you will get reference error
Const
It allows you to be immutable with variables.
Const declarations must be initialized
const name; // ERROR: const declarations must be initialized
A const is block scoped like we saw with let:+
const num = 10;
if (true) {
const num = 20; // Allowed as its a new variable limited to this `if` block
}
/*
// declaration of const in same block scope is not allowed
const a = 10;
const a = 15; //Redeclaration of const a Error
console.log(`const outer value `+a);
*/
/*
//declaration of const in different block scope is allowed
const a = 10;
console.log(`outer value of a `+a)
{
const a = 15; //Redeclaration of const allowed in different block scope
console.log(`ineer value of a `+a);
}
*/
/*
// re assigning const variable in any block scope is not allowed
const a = 10;
a = 15; //invalid assignment to const 'a'
{
a = 15; //invalid assignment to const 'a'
}
*/
/*
// let also can not be re declared in the same block scope
let a = 10;
let a = 15; //SyntaxError: redeclaration of let a
*/
/*
// let can be redeclared in different block scope
let a = 10;
{
let a = 15; //allowed.
}
*/
/*
// let can be re assigned in same block or different block
let a = 10;
a = 15; //allowed for let but for const its not allowed.
*/
/*
let a = 10;
{
a = 15; //allowed
}
*/
Related
console.log(x)
var x = 10;
The console gives me undefined but I was expected reference error
var is the old way of declaring a variable in JS. It has a few properties that you should consider in comparison to what let and const let you do.
Your variable declaration var x = 10 will be raised up to the top of the script, as a function declaration on the other hand is hoisted by the JS engine during compilation. However, ONLY the declaration is hoisted and the variable will be assigned undefined until you assign to it another value manually using the assignment operator =.
JS engine doesn't throw a ReferenceError because your code is translated (using hoisting) into
var x;
console.log(x);
x = 10;
At the same time, var doesn't have the concept of block scope, so at the same time the code below is running just fine
console.log(x);
{
var x = 10;
}
The code above is being translated (using hoisting) into
var x;
console.log(x);
{
x = 10;
}
If a variable is used in code and then declared and initialized, the value when it is used will be its default initialization (undefined for a variable declared using var, use const and let to avoid this).
I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...
console.log(typeof name); // undefined
var name = "John";
...variables declared with let or const seem to have some problems with hoisting:
console.log(typeof name); // ReferenceError
let name = "John";
and
console.log(typeof name); // ReferenceError
const name = "John";
Does this mean that variables declared with let or const are not hoisted? What is really going on here? Is there any difference between let and const in this matter?
#thefourtheye is correct in saying that these variables cannot be accessed before they are declared. However, it's a bit more complicated than that.
Are variables declared with let or const not hoisted? What is really going on here?
All declarations (var, let, const, function, function*, class) are "hoisted" in JavaScript. This means that if a name is declared in a scope, in that scope the identifier will always reference that particular variable:
x = "global";
// function scope:
(function() {
x; // not "global"
var/let/… x;
}());
// block scope (not for `var`s):
{
x; // not "global"
let/const/… x;
}
This is true both for function and block scopes1.
The difference between var/function/function* declarations and let/const/class declarations is the initialisation.
The former are initialised with undefined or the (generator) function right when the binding is created at the top of the scope. The lexically declared variables however stay uninitialised. This means that a ReferenceError exception is thrown when you try to access it. It will only get initialised when the let/const/class statement is evaluated, everything before (above) that is called the temporal dead zone.
x = y = "global";
(function() {
x; // undefined
y; // Reference error: y is not defined
var x = "local";
let y = "local";
}());
Notice that a let y; statement initialises the variable with undefined like let y = undefined; would have.
The temporal dead zone is not a syntactic location, but rather the time between the variable (scope) creation and the initialisation. It's not an error to reference the variable in code above the declaration as long as that code is not executed (e.g. a function body or simply dead code), and it will throw an exception if you access the variable before the initialisation even if the accessing code is below the declaration (e.g. in a hoisted function declaration that is called too early).
Is there any difference between let and const in this matter?
No, they work the same as far as hoisting is regarded. The only difference between them is that a constant must be and can only be assigned in the initialiser part of the declaration (const one = 1;, both const one; and later reassignments like one = 2 are invalid).
1: var declarations are still working only on the function level, of course
Quoting ECMAScript 6 (ECMAScript 2015) specification's, let and const declarations section,
The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated.
So, to answer your question, yes, let and const hoist but you cannot access them before the actual declaration is evaluated at runtime.
ES6 introduces Let variables which comes up with block level scoping. Until ES5 we did not have block level scoping, so the variables which are declared inside a block are always hoisted to function level scoping.
Basically Scope refers to where in your program your variables are visible, which determines where you are allowed to use variables you have declared. In ES5 we have global scope,function scope and try/catch scope, with ES6 we also get the block level scoping by using Let.
When you define a variable with var keyword, it's known the entire function from the moment it's defined.
When you define a variable with let statement it's only known in the block it's defined.
function doSomething(arr){
//i is known here but undefined
//j is not known here
console.log(i);
console.log(j);
for(var i=0; i<arr.length; i++){
//i is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
for(let j=0; j<arr.length; j++){
//j is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
}
doSomething(["Thalaivar", "Vinoth", "Kabali", "Dinesh"]);
If you run the code, you could see the variable j is only known in the loop and not before and after. Yet, our variable i is known in the entire function from the moment it is defined onward.
There is another great advantage using let as it creates a new lexical environment and also binds fresh value rather than keeping an old reference.
for(var i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
for(let i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
The first for loop always print the last value, with let it creates a new scope and bind fresh values printing us 1, 2, 3, 4, 5.
Coming to constants, it work basically like let, the only difference is their value can't be changed. In constants mutation is allowed but reassignment is not allowed.
const foo = {};
foo.bar = 42;
console.log(foo.bar); //works
const name = []
name.push("Vinoth");
console.log(name); //works
const age = 100;
age = 20; //Throws Uncaught TypeError: Assignment to constant variable.
console.log(age);
If a constant refers to an object, it will always refer to the object but the object itself can be changed (if it is mutable). If you like to have an immutable object, you could use Object.freeze([])
As per ECMAScript® 2021
Let and Const Declarations
let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.
The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.
A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created.
If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.
Block Declaration Instantiation
When a Block or CaseBlock is evaluated a new declarative Environment Record is created and bindings for each block scoped variable, constant, function, or class declared in the block are instantiated in the Environment Record.
No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.
Top Level Lexically Declared Names
At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.
Conclusion
let and const are hoisted but not initialized.
Referencing the variable in the block before the variable declaration results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
Examples below make it clear as to how "let" variables behave in a lexical scope/nested-lexical scope.
Example 1
var a;
console.log(a); //undefined
console.log(b); //undefined
var b;
let x;
console.log(x); //undefined
console.log(y); // Uncaught ReferenceError: y is not defined
let y;
The variable 'y' gives a referenceError, that doesn't mean it's not hoisted. The variable is created when the containing environment is instantiated. But it may not be accessed bcz of it being in an inaccessible "temporal dead zone".
Example 2
let mylet = 'my value';
(function() {
//let mylet;
console.log(mylet); // "my value"
mylet = 'local value';
})();
Example 3
let mylet = 'my value';
(function() {
let mylet;
console.log(mylet); // undefined
mylet = 'local value';
})();
In Example 3, the freshly declared "mylet" variable inside the function does not have an Initializer before the log statement, hence the value "undefined".
Source
ECMA
MDN
From MDN web docs:
In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
console.log(x); // ReferenceError
let x = 3;
in es6 when we use let or const we have to declare the variable before using them.
eg. 1 -
// this will work
u = 10;
var u;
// this will give an error
k = 10;
let k; // ReferenceError: Cannot access 'k' before initialization.
eg. 2-
// this code works as variable j is declared before it is used.
function doSmth() {
j = 9;
}
let j;
doSmth();
console.log(j); // 9
let and const are also hoisted.
But an exception will be thrown if a variable declared with let or const is read before it is initialised due to below reasons.
Unlike var, they are not initialised with a default value while hoisting.
They cannot be read/written until they have been fully initialised.
I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...
console.log(typeof name); // undefined
var name = "John";
...variables declared with let or const seem to have some problems with hoisting:
console.log(typeof name); // ReferenceError
let name = "John";
and
console.log(typeof name); // ReferenceError
const name = "John";
Does this mean that variables declared with let or const are not hoisted? What is really going on here? Is there any difference between let and const in this matter?
#thefourtheye is correct in saying that these variables cannot be accessed before they are declared. However, it's a bit more complicated than that.
Are variables declared with let or const not hoisted? What is really going on here?
All declarations (var, let, const, function, function*, class) are "hoisted" in JavaScript. This means that if a name is declared in a scope, in that scope the identifier will always reference that particular variable:
x = "global";
// function scope:
(function() {
x; // not "global"
var/let/… x;
}());
// block scope (not for `var`s):
{
x; // not "global"
let/const/… x;
}
This is true both for function and block scopes1.
The difference between var/function/function* declarations and let/const/class declarations is the initialisation.
The former are initialised with undefined or the (generator) function right when the binding is created at the top of the scope. The lexically declared variables however stay uninitialised. This means that a ReferenceError exception is thrown when you try to access it. It will only get initialised when the let/const/class statement is evaluated, everything before (above) that is called the temporal dead zone.
x = y = "global";
(function() {
x; // undefined
y; // Reference error: y is not defined
var x = "local";
let y = "local";
}());
Notice that a let y; statement initialises the variable with undefined like let y = undefined; would have.
The temporal dead zone is not a syntactic location, but rather the time between the variable (scope) creation and the initialisation. It's not an error to reference the variable in code above the declaration as long as that code is not executed (e.g. a function body or simply dead code), and it will throw an exception if you access the variable before the initialisation even if the accessing code is below the declaration (e.g. in a hoisted function declaration that is called too early).
Is there any difference between let and const in this matter?
No, they work the same as far as hoisting is regarded. The only difference between them is that a constant must be and can only be assigned in the initialiser part of the declaration (const one = 1;, both const one; and later reassignments like one = 2 are invalid).
1: var declarations are still working only on the function level, of course
Quoting ECMAScript 6 (ECMAScript 2015) specification's, let and const declarations section,
The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated.
So, to answer your question, yes, let and const hoist but you cannot access them before the actual declaration is evaluated at runtime.
ES6 introduces Let variables which comes up with block level scoping. Until ES5 we did not have block level scoping, so the variables which are declared inside a block are always hoisted to function level scoping.
Basically Scope refers to where in your program your variables are visible, which determines where you are allowed to use variables you have declared. In ES5 we have global scope,function scope and try/catch scope, with ES6 we also get the block level scoping by using Let.
When you define a variable with var keyword, it's known the entire function from the moment it's defined.
When you define a variable with let statement it's only known in the block it's defined.
function doSomething(arr){
//i is known here but undefined
//j is not known here
console.log(i);
console.log(j);
for(var i=0; i<arr.length; i++){
//i is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
for(let j=0; j<arr.length; j++){
//j is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
}
doSomething(["Thalaivar", "Vinoth", "Kabali", "Dinesh"]);
If you run the code, you could see the variable j is only known in the loop and not before and after. Yet, our variable i is known in the entire function from the moment it is defined onward.
There is another great advantage using let as it creates a new lexical environment and also binds fresh value rather than keeping an old reference.
for(var i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
for(let i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
The first for loop always print the last value, with let it creates a new scope and bind fresh values printing us 1, 2, 3, 4, 5.
Coming to constants, it work basically like let, the only difference is their value can't be changed. In constants mutation is allowed but reassignment is not allowed.
const foo = {};
foo.bar = 42;
console.log(foo.bar); //works
const name = []
name.push("Vinoth");
console.log(name); //works
const age = 100;
age = 20; //Throws Uncaught TypeError: Assignment to constant variable.
console.log(age);
If a constant refers to an object, it will always refer to the object but the object itself can be changed (if it is mutable). If you like to have an immutable object, you could use Object.freeze([])
As per ECMAScript® 2021
Let and Const Declarations
let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.
The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.
A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created.
If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.
Block Declaration Instantiation
When a Block or CaseBlock is evaluated a new declarative Environment Record is created and bindings for each block scoped variable, constant, function, or class declared in the block are instantiated in the Environment Record.
No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.
Top Level Lexically Declared Names
At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.
Conclusion
let and const are hoisted but not initialized.
Referencing the variable in the block before the variable declaration results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
Examples below make it clear as to how "let" variables behave in a lexical scope/nested-lexical scope.
Example 1
var a;
console.log(a); //undefined
console.log(b); //undefined
var b;
let x;
console.log(x); //undefined
console.log(y); // Uncaught ReferenceError: y is not defined
let y;
The variable 'y' gives a referenceError, that doesn't mean it's not hoisted. The variable is created when the containing environment is instantiated. But it may not be accessed bcz of it being in an inaccessible "temporal dead zone".
Example 2
let mylet = 'my value';
(function() {
//let mylet;
console.log(mylet); // "my value"
mylet = 'local value';
})();
Example 3
let mylet = 'my value';
(function() {
let mylet;
console.log(mylet); // undefined
mylet = 'local value';
})();
In Example 3, the freshly declared "mylet" variable inside the function does not have an Initializer before the log statement, hence the value "undefined".
Source
ECMA
MDN
From MDN web docs:
In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
console.log(x); // ReferenceError
let x = 3;
in es6 when we use let or const we have to declare the variable before using them.
eg. 1 -
// this will work
u = 10;
var u;
// this will give an error
k = 10;
let k; // ReferenceError: Cannot access 'k' before initialization.
eg. 2-
// this code works as variable j is declared before it is used.
function doSmth() {
j = 9;
}
let j;
doSmth();
console.log(j); // 9
let and const are also hoisted.
But an exception will be thrown if a variable declared with let or const is read before it is initialised due to below reasons.
Unlike var, they are not initialised with a default value while hoisting.
They cannot be read/written until they have been fully initialised.
I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...
console.log(typeof name); // undefined
var name = "John";
...variables declared with let or const seem to have some problems with hoisting:
console.log(typeof name); // ReferenceError
let name = "John";
and
console.log(typeof name); // ReferenceError
const name = "John";
Does this mean that variables declared with let or const are not hoisted? What is really going on here? Is there any difference between let and const in this matter?
#thefourtheye is correct in saying that these variables cannot be accessed before they are declared. However, it's a bit more complicated than that.
Are variables declared with let or const not hoisted? What is really going on here?
All declarations (var, let, const, function, function*, class) are "hoisted" in JavaScript. This means that if a name is declared in a scope, in that scope the identifier will always reference that particular variable:
x = "global";
// function scope:
(function() {
x; // not "global"
var/let/… x;
}());
// block scope (not for `var`s):
{
x; // not "global"
let/const/… x;
}
This is true both for function and block scopes1.
The difference between var/function/function* declarations and let/const/class declarations is the initialisation.
The former are initialised with undefined or the (generator) function right when the binding is created at the top of the scope. The lexically declared variables however stay uninitialised. This means that a ReferenceError exception is thrown when you try to access it. It will only get initialised when the let/const/class statement is evaluated, everything before (above) that is called the temporal dead zone.
x = y = "global";
(function() {
x; // undefined
y; // Reference error: y is not defined
var x = "local";
let y = "local";
}());
Notice that a let y; statement initialises the variable with undefined like let y = undefined; would have.
The temporal dead zone is not a syntactic location, but rather the time between the variable (scope) creation and the initialisation. It's not an error to reference the variable in code above the declaration as long as that code is not executed (e.g. a function body or simply dead code), and it will throw an exception if you access the variable before the initialisation even if the accessing code is below the declaration (e.g. in a hoisted function declaration that is called too early).
Is there any difference between let and const in this matter?
No, they work the same as far as hoisting is regarded. The only difference between them is that a constant must be and can only be assigned in the initialiser part of the declaration (const one = 1;, both const one; and later reassignments like one = 2 are invalid).
1: var declarations are still working only on the function level, of course
Quoting ECMAScript 6 (ECMAScript 2015) specification's, let and const declarations section,
The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated.
So, to answer your question, yes, let and const hoist but you cannot access them before the actual declaration is evaluated at runtime.
ES6 introduces Let variables which comes up with block level scoping. Until ES5 we did not have block level scoping, so the variables which are declared inside a block are always hoisted to function level scoping.
Basically Scope refers to where in your program your variables are visible, which determines where you are allowed to use variables you have declared. In ES5 we have global scope,function scope and try/catch scope, with ES6 we also get the block level scoping by using Let.
When you define a variable with var keyword, it's known the entire function from the moment it's defined.
When you define a variable with let statement it's only known in the block it's defined.
function doSomething(arr){
//i is known here but undefined
//j is not known here
console.log(i);
console.log(j);
for(var i=0; i<arr.length; i++){
//i is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
for(let j=0; j<arr.length; j++){
//j is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
}
doSomething(["Thalaivar", "Vinoth", "Kabali", "Dinesh"]);
If you run the code, you could see the variable j is only known in the loop and not before and after. Yet, our variable i is known in the entire function from the moment it is defined onward.
There is another great advantage using let as it creates a new lexical environment and also binds fresh value rather than keeping an old reference.
for(var i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
for(let i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
The first for loop always print the last value, with let it creates a new scope and bind fresh values printing us 1, 2, 3, 4, 5.
Coming to constants, it work basically like let, the only difference is their value can't be changed. In constants mutation is allowed but reassignment is not allowed.
const foo = {};
foo.bar = 42;
console.log(foo.bar); //works
const name = []
name.push("Vinoth");
console.log(name); //works
const age = 100;
age = 20; //Throws Uncaught TypeError: Assignment to constant variable.
console.log(age);
If a constant refers to an object, it will always refer to the object but the object itself can be changed (if it is mutable). If you like to have an immutable object, you could use Object.freeze([])
As per ECMAScript® 2021
Let and Const Declarations
let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.
The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.
A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created.
If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.
Block Declaration Instantiation
When a Block or CaseBlock is evaluated a new declarative Environment Record is created and bindings for each block scoped variable, constant, function, or class declared in the block are instantiated in the Environment Record.
No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.
Top Level Lexically Declared Names
At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.
Conclusion
let and const are hoisted but not initialized.
Referencing the variable in the block before the variable declaration results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
Examples below make it clear as to how "let" variables behave in a lexical scope/nested-lexical scope.
Example 1
var a;
console.log(a); //undefined
console.log(b); //undefined
var b;
let x;
console.log(x); //undefined
console.log(y); // Uncaught ReferenceError: y is not defined
let y;
The variable 'y' gives a referenceError, that doesn't mean it's not hoisted. The variable is created when the containing environment is instantiated. But it may not be accessed bcz of it being in an inaccessible "temporal dead zone".
Example 2
let mylet = 'my value';
(function() {
//let mylet;
console.log(mylet); // "my value"
mylet = 'local value';
})();
Example 3
let mylet = 'my value';
(function() {
let mylet;
console.log(mylet); // undefined
mylet = 'local value';
})();
In Example 3, the freshly declared "mylet" variable inside the function does not have an Initializer before the log statement, hence the value "undefined".
Source
ECMA
MDN
From MDN web docs:
In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
console.log(x); // ReferenceError
let x = 3;
in es6 when we use let or const we have to declare the variable before using them.
eg. 1 -
// this will work
u = 10;
var u;
// this will give an error
k = 10;
let k; // ReferenceError: Cannot access 'k' before initialization.
eg. 2-
// this code works as variable j is declared before it is used.
function doSmth() {
j = 9;
}
let j;
doSmth();
console.log(j); // 9
let and const are also hoisted.
But an exception will be thrown if a variable declared with let or const is read before it is initialised due to below reasons.
Unlike var, they are not initialised with a default value while hoisting.
They cannot be read/written until they have been fully initialised.
I declared variables twice in my function while I am using "use strict". I know this function has global scope and it's variables are also treated as global with window scope i.e window.car
But It should not re-declare speed and capacity variables inside if statement with let data type. ( "let" Declares a block scope local variable, optionally initializing it to a value. )
(function car() {
"use strict";
var speed = 100;
const capacity = '1000CC';
if(speed) {
let speed = 200;
let capacity = '5000CC';
console.log(speed,capacity);
}
console.log(speed,capacity);
})();
Please let me know what I am missing here.
"let" Declares a block scope local variable. But still global variable can be modified in local scope.
(function car() {
"use strict";
var speed = 100;
const capacity = '1000CC';
if(speed) {
let speed = 200;
let capacity = '5000CC';
console.log(speed,capacity);//inside local it is modified to 200
}
console.log(speed,capacity);//outside scope it pull from global scope to 100
})();
You can re-declare / modify the global variables even in strict mode.
You'll only get error when you re-declare the same variable in same scope. Look at the following example taken from MDN
if (x) {
let foo;
let foo; // TypeError thrown.
}
However, function bodies do not have this limitation! (But it throws an error in ES6 though as commented by #Bergi, may be there's wrong documentation in MDN)
function do_something() {
let foo;
let foo; // This works fine.
}
The variable speed declared with var and the speed declared with let are two different variables.
Inside the body of the if statement, the local declaration of speed hides the variable declared in the outer block - it doesn't redeclare it.