Var vs Let vs Const in JavaScript.
In this article, I am going to explain some new features, introduced with the ES2015 (ES6) version of JavaScript. Let's get started.
Prerequisites
Before starting this article, you need to know some basic concepts that will help you to further understand the advanced concepts that we would be discussing. For that you can refer to my previous article:
Introduction
JavaScript is the world's most popular programming language and is also called the programming language of the Web. It is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it like, such as Node.js, ApacheCouchDB and many more. It is a multi-paradigm, single-threaded, dynamic language, supporting object-oriented and declarative styles.
ECMAScript 2015 was the second major revision to JavaScript and is also known as ES6 and ECMAScript 6.
New Features in ES6
The let keyword
The const keyword
Arrow Functions
The ... Operator
For/of
Map Objects
Set Objects
Classes
Promises
Parameters
JavaScript Modules
and much more.
In the ES6 version of JavaScript, two new keywords for the variable declaration were introduced (let & const) as already discussed above. Earlier, only var was used to declare variables, but was the need for two new keywords, and why were they introduced?
In this article, we will try to understand the differences, what to use when, and what are the advantages of using let and const over var. We will discuss them in respect of hoisting, use, and scope.
But, first, let's understand Scope and its type.
Scope
In JavaScript, scope refers to the accessibility or visibility of the variables and other declarations within the code. Before ES6 (2015), JavaScript had only Global Scope and Function Scope. It introduced two new keywords: let
and const
. These two keywords provide Block Scope in JavaScript.
Global Scope:
A variable declared outside a function becomes GLOBAL.
let name = "BMW";
// code here can use name
function myFunction(){
// code here can also use name
}
A global variable has Global Scope: All scripts and functions on a web page can access it.
Function Scope:
Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function.
function myName(){
var name = "BMW"; // Function Scope
}
Block Scope:
Let and const keywords provide Block Scope in JavaScript. Variables declared inside a { } block cannot be accessed from outside the block:
{
let num = 10;
}
// num cannot be used outside.
Variables declared with var
keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
{
var num = 10;
}
// num can be used here
Now that we are equipped with the knowledge of Scope, let's understand Hoisting too so that we can understand var, let, and const in good detail.
Hoisting
JavaScript declarations are hoisted i.e., a variable can be declared after it has been used. In other words; a variable can be used before it has been declared.
Example 1 and Example 2 give the same result:
// Example 1
num = 15; // Assign 15 to num
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = num; // Display num in the element
var num ; // Declare x
// Example 2
var num; // Declare num
num = 15; // Assign 15 to num
elem = document.getElementById("demo"); // FInd an element
elem.innerHTML = num; // Display num in the element
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
So now, we know both hoisting and scope, and can move forward to understand var, let and const in JavaScript.
Var
The scope of a var variable is functional scope. It can be updated and re-declared into the scope. It can be declared without initialization. It can be accessed without initialization as its default value is "undefined". Hoisting is done with initializing as the default value.
// Re-declaration
var name = "Mrinmoy";
name = "Porel";
console.log(name); // Output: Porel
// Variable updated
var num = 10;
num = 20;
console.log(num); // Output: 20
Let
The scope of a let variable is block scope. It can be updated but cannot be re-declared into the scope. It can be declared without initialization. It cannot be accessed without initialization otherwise it will give 'referenceError'. Hoisting is done, but not initialized, this is the reason for the error when we access the let variable before declaration/ initialization.
// declaring and assigning variable with let.
let quote = "I Love JavaScript.";
console.log(quote); //output: I Love JavaScript.
if(true){
let name = "Mrinmoy";
console.log(name); //output: Mrinmoy
}
console.log(name); // output: ReferenceError: name is not defined
Const
The scope of a const variable is block scope. It cannot be updated or re-declared into the scope. It cannot be declared without initialization. It cannot be accessed without initialization, as it cannot be declared without initialization. Hoisting is done, but not initialized, this is the reason for the error when we access the const variable before declaration/initialization.
if(true){
const day = "Sunday";
console.log(day); //output: Sunday
}
console.log(day); // ReferenceError: day is not defined
const month ="January";
const month = "June";
// SyntaxError: Identifier 'month' has already been declared
const month = "December";
month = "January";
//output: TypeError: Assignment to constant variable.
const person1 = {
name: 'Mrinmoy',
age: '23',
}
console.log(person1); //output: { name: 'Mrinmoy', age: 23 }
person1.name = "Max"
console.log(person1); // output: { name: 'Max', age: 23 }
Conclusion
That's the story behind let
, const
, and var
. It is one of the fastest evolving languages, in terms of practices, tooling, and ecosystem.
If you enjoyed learning and find it useful please do like and share so that, it reaches others as well π€.
Thanks for reading π
I would β€ to connect with you on Twitter | LinkedIn | GitHub Let me know in the comment section if you have any doubts or feedback.