In this post, We are going to understand JavaScript ES6 const and let keywords with examples. Also, we will learn about how and where to use them and what are the limitations of var statement.
What are the limitations of var statement?
- The scope of the var is global if declared outside the function.
- declaring var inside a function makes it valid in function-scope.
- The value of a variable can be reassigned & declared using var.
- var variable are hoisting(It is a java script mechanism where variable are moved to top of its scope before execution)and initialize with value of undefined.
To overcome all these limitations, ES6 Introduced the let keyword.
ES6 Two new ways to declare variable
In ES6 Introduced two new ways to declare variables. Before ES6, we used to declare variables using var, var allows us to declare variables based on two scopes (local and global) and (global, function).
let and const allow us to declare block scope variable.
- let
- const
Let Statement
let Statement makes us declare a variable whose scope is in the code block(code inside {}braces) or expression in it is used. If let is declared globally or topmost then it does not create the property of a global object(Window).
1.1. Let has code block Scope
Declaring a variable with let make its scope with a block in which let is declare also in sub-block.
let: In this example, we assigned t=5 out of the block, later we assigned t=6 in the block. Every time we are getting different output.
Var: In case of var scope is global we assigned s=1 & later s=2, it considers it the same variable and assigns a new value to variable s. So getting the same output, Inside or outside the block.
//var behavior
//hoisting of s
console.log(s);
var s = 1;
{
var s = 2; //same variable
console.log('var in the code-block = '+s);
}
console.log('var out the code-block = '+s);
//let behavior
let t= 5
if(t==5)
{
let t = 6; //another variable
console.log(' let with in the code-block = '+t);
}
console.log(' let outside the code-block = ' +t);
Output
undefined
var in the block = 2
var out the block = 2
let with in the code-block = 6
let outside the code-block = 5
1.2. Let property Scope with global Object (window)
let does not create a property with the global objects. We will understand with an example.
var var_glob = '10';
let let_glob = '20';
console.log(window.var_glob);
console.log(window.let_glob);
Output
10
undefined
1. 3. Redeclaration variable behavior
a variable declared with let can’t be redeclared within function or code block. Although it can be reassigned. if we do so, We will get SyntaxError
We will understand this with an example
for(i=0;i<=5;i++)
{
let j = 0;
let j = 7
j=10; //re initialization can be done
}
Output
SyntaxError: Identifier 'j' has already been declared
However, we can declare the same variable in the sub-block without any error. Because the variable is treated as a new variable in sub-block, has a different scope.
let i = 10;
if (true) {
let i = 20;
console.log(i);
}
console.log(i);
Output
20
10
1. 4. Temporal dead zone with Let
Variables declared with let and var are hoisted to the top. As we went through, variable declared with var & initialized with undefined. Whereas variables declared with let are not initialized, accessing variables declared with let before initialization will throw ReferenceError.
We will understand better with Example
function scope() {
console.log(a);
console.log(b);
var a = 12;
let b = 22;
}
console.log(scope())
Output
undefined
ReferenceError: Cannot access 'b' before initialization
2.const statement
If we declare a variable with const statement, it makes their scope global or local to the code block in which it is declared same as let statement
const VARIABLE_NAME= value;
The name of the const variable name can be lower or upper case. It is a convention to use all upper letters.
Important point
- const does not create a property with global object (window).
- const can’t be redeclared or reassigned.
- const variable need to initialize during declaration otherwise it throws error.
- const make the variable value read only .It is immutable.
Example : const can’t be re declare or reassign.
//assigning PRICE again throwing an error.
const PRICE = 500;
PRICE = 400;
Output
TypeError: Assignment to constant variable.
Example : const variable need to initialize during declaration
const PRICE;
Output
SyntaxError: Missing initializer in const declaration
2.1 const with objects
In this case, a const variable identifier is an object. Its property can be modified. Let us understand with an example, by modifying the object property
Program example
const groceries= { bread: 20,potatoes:40};
groceries.bread = 30;
groceries.potatoes =60;
console.log(`object modified property = ${groceries.bread}`)
console.log(`object modified property = ${groceries.potatoes}`)
Output
object modified property = 30
object modified property = 60
Reassign the const object will throw an error
const groceries= { bread: 20,potatoes:40};
groceries = {tomato:10};
Output
TypeError: Assignment to constant variable.
2.2 const with Array
In this case, the const variable identifier is an Array. Its value can be modified. Let us understand with an example, by modifying Array’s values.
const groceries= [ 'bread','potatoes'];
groceries[0] = 'sugar';
groceries[1] = 'biscuits'
console.log(`Array's values =\n ${groceries[0]}\n ${groceries[1]}`);
Output
Array's values =
sugar
biscuits
Reassigning the Array will throw a type error.
Let us understand the same with an example.
const groceries= [ 'bread','potatoes'];
groceries = ['test','test2'];
Output
TypeError: Assignment to constant variable
Different between let and const
- const can’t redeclare and reassign in same scope.Whereas let can be reassign.
- const is immutable,once it is declared,it can’t be modified except with objects and Array properties can be modified.let can be mutable.
- const need to be initialized during declaration, but let does not need to be initialized.
Similarity between Let and const
- let and const don’t create global object property(window).
- const behavior is same as let with Temporal dead zone
- let and const have block scope except let can be reassigned in block or re-declare in sub-block.
Summary :
We have explored JavaScript ES6 const and let. Also, we learned Where and how to use them.