Photo by Clément Hélardot on Unsplash
Understanding Var, Let, and Const in JavaScript. (With Examples)
by Himanshu Kesarwani.
Javascript is one of the most popular programming languages. Javascript has numerous applications in almost every field. It is the language that gives life to the website across the internet.
JavaScript is used for adding functionality to any site. HTML is for the skeleton and CSS is for styling.
Almost all major browsers go well with JavaScript with a dedicated JavaScript engine to run the code on the user's device. As of 2022, 98% of websites in the world use JavaScript for the client side.
Some new features were introduced with the ES2015 (ES6) version of JavaScript. One of the features was the addition of two new keywords, let and const for variable declaration. Earlier, only var was used to declare variables. But what was the need for the 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 first and its type.
Scope:
In JavaScript, scope refers to the accessibility or visibility of the variables and other declarations within the code. There are three types of scope, namely, global scope, function scope, and block scope.
Block Scope.
A group of statements enclosed within a set of curly brackets is called a block. In layman's terms, Block-scoped variables mean the life of that variable exists in that block of code only. It is only accessible in that block of code in which it is declared and cannot be accessed from the outside of the block.
if(true){
let x = 5;
console.log(x); // 5
}
console.log(x) // ReferenceError: x is not defined
// x cannot be accessed here as it is only accessible in that block only.
Functional Scope:
Function Scoped means the life of that variable exists in that function only. It can be accessed in any block or nested function within the same function but not outside the function's body.
function forExample(){
let x = 2;
console.log(x); // output: 2
}
forExample(); // function call
console.log(x); // ReferenceError: x is not defined
// This happens because x is defined and only accessible in that function not outside the body of the function.
Global Scope:
Variables declared outside of any function have global scope. They can be accessed from anywhere in the program. Global Scope means that the life of the variable is in the entire program not to any particular block or function.
All scripts and functions can easily access them.
let x = 25; // x is global scope variable
function test(){
x+=2; // x is accessible from inside of a function and increased by 2
console.log(x); // 27
if(true){
x+=5; // x is accessible in block too and increased by 5.
console.log(x); // 32
}
}
test(); // function call
console.log(x); // 32
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.
Hoisting is the behavior of moving declarations of variables and functions to the top of the current scope. It helps to execute declarations before any other code.
In other words, Hoisting is a concept in JavaScript that allows using variables and functions even before they are declared. Basically, they are moved to the top of their scope before code execution.
Let's understand this with the help of the following code.
console.log(x) // undefined
var x = 2;
The code output is not defined, but it does not throw an error because of the magical effect of Hoisting.
JavaScript interpreter separates the declaration from the assignment of variables and functions and hoists the declaration at the top of the containing scope before the execution.
So, In the above example due to hoisting, we are able to use the variable 'x' even before declaring it because the declaration part of the variable is automatically hoisted at the top.
The same code behaves like this,
var x;
console.log(x); // undefined
x = 2;
Now, we know both, we can move further and understand the three magical words in JavaScript,
var, let, and const.
Var
Var is a keyword that is used to declare variables in JavasScript. Earlier only the var keyword was used for a variable declaration that is before the introduction of ES6.
It can be re-declared and updated. Hence we can redeclare the same variable again and update it too.
// Re-declaration
var str = "Good";
var str = "Day"
console.log(str); // output: Day
// variable updated
var a = 2;
a = 10;
console.log(a); // output: 10
Here, we have redeclared the global variable, str
and assigned it a value of "Day
".
- var declarations are globally or functionally scoped.
var abc = 22;
function example(){
var xyz = 59;
console.log(xyz);
}
console.log(abc);
console.log(xyz); // ReferenceError: xyz is not defined.
Here variable xyz
is functional scoped and cannot be accessed out of the body of the function.
- variables declared with
var
are hoisted to the top with a value of undefined.
Main Issue with var:
Let us try to understand the problem of using var for variable declaration with the help of the following code.
var phone = "keypad";
console.log(phone);
haveMoney = true;
if(haveMoney) {
var phone = "iPhone 14";
}
console.log(phone);
Here, if the if condition
is true, we will redeclare the variable phone
and assign it a value of "iPhone 14".
This is not a problem if we are doing it willingly and we know about it. But there can be situations where this becomes a headache and can lead to accidental bugs added to our code. As the output will not come according to our choice if we have this variable somewhere else in the code.
Let
But as we saw, var has some issues associated with it and that is why new keywords were needed.
- Let is a new keyword introduced with the ES6 version of JavaScript. It is now the preferred way to declare variables. It solves the issue that we encountered with var.
// declaring and assigning variable with let.
let x = "I Love JavaScript.";
console.log(x); //output: I Love JavaScript.
- let is block scoped and is only confined to the block in which it is defined.
if(true){
let name = "Himanshu";
console.log(name); //output: Himanshu
}
console.log(name); // output: ReferenceError: name is not defined
Here is the example, we used a variable name
outside the block and it showed an error.
- let cannot be re-declared and can only be updated within its scope.
This code will work as variables can be updated.
let b = 34;
b = 35;
console.log(b); //output: 35
This code will throw up an error as it cannot be declared.
let a = 2;
console.log(a);
let a = 4;
console.log(a); // output: SyntaxError: Identifier 'a' has already been declared.
- let variables are also hoisted to the top of their current scope, but unlike var, let is not initialized to undefined. It will rather give a reference error.
console.log(x)
let x = 3; // output: ReferenceError: x is not defined
Const.
The Const keyword is used to define constant values.
Just like let, const is also block scoped and cannot be accessed from outside of the block.
if(true){
const day = "Monday";
console.log(day); //output: Monday
}
console.log(day); // ReferenceError: day is not defined
Here, we cannot access day from the outside of the block.
- It cannot be re-declared or updated. Variables declared remain constant and cannot be changed.
const month ="November";
const month = "May";
// SyntaxError: Identifier 'month' has already been declared
const month = "December";
month = "January";
//output: TypeError: Assignment to constant variable.
As we can see, we cannot re-declare or update the value of the variable. However, when we declare an object with const, we can still update its properties. For example,
const person1 = {
name: 'Alex',
age: '23',
}
console.log(person1); //output: { name: 'Alex', age: 23 }
person1.name = "Ajay"
console.log(person1); // output: { name: 'Ajay', age: 23 }
- Const is hoisted to the top of their scope but is not initialized with undefined.
So finally we come to the end, I hope the blog was helpful, do let me know if there are suggestions/corrections in the comments.
Have a Nice day!
Keep Learning!
Checkout my other article too, (5 min read)
A list of Top Free Resources for Developers (Channels, Repositories, Blogs, and much more.)