Understanding of Var, let & const
Var be like : Kya mai Itna bura hoo mai javascript π₯
A lot of new features came out as part of ES6, which make the life of a javascript developer easy. One of the features that came with ES6 is the addition of let and const which can be used for variable declaration. But before going in-depth let's get some basic understanding of what is variable after which it will be much easier for us to understand the concepts of var, let & const.
What is a Variable?
Variables are buckets in memory that stores value. Later with help of this variable we will be able to access values.
var a = 1;
console.log(a); //output - 1
var name = "Akash";
console.log(name); //Output - Akash
What is Var
in Javascript?
Var is the keyword that helps to create a variable in javascript. Before ES6, var was widely used in production code to create variables. There were many issues associated with declaring variables with var which is still there due to the legacy of Javascript. That is why it was necessary for new ways to declare variables in javascript.
Scope of var
Scope essentially means where these variables are available for use. var declarations function/locally scoped or are globally scoped. The scope is global when a var variable is declared outside a function. This means that any variable that is declared with var outside a function block is available for use in the whole window which means that is globally scoped.
var is a function scoped when it is declared within a function. This means that it is available and can be accessed only within that function. once the functions get over variable is not accessible anymore.
For Example,
var firstName = "Akash";
var age = 22;
function fullname (){
var lastName = "Singh";
}
Here in the above example, variables firstName and age are declared outside function so these variables have a global scope which means they can be accessed from anywhere. Variable lastName is declared inside function fullName so the scope of the variable lastName is function scoped which means once the function fullName gets over the variable lastName is no more accessible anywhere. If we try to access lastName outside the function fullName it will throw an error.
Hoisting of var
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:
console.log (name);
var name = "Akash Kumar Singh"
it is interpreted as this:
var name;
console.log(name); // name is undefined
name = "Akash Kumar Singh"
So var
variables are hoisted to the top of their scope and initialized with a value of undefined
.
Problem with var
There's a weakness that comes with var. I'll use the example below to explain:
var greeter = "hey hi";
var times = 4;
if (times > 3) {
var greeter = "say Hello instead";
}
console.log(greeter) // "say Hello instead"
So, since times > 3
returns true, greeter
is redefined to "say Hello instead"
. While this is not a problem if you knowingly want greeter
to be redefined, it becomes a problem when you do not realize that a variable greeter
has already been defined before.
If you have used greeter
in other parts of your code, you might be surprised at the output you might get. This will likely cause a lot of bugs in your code. This is why let
and const
are necessary.
Introduction to let
let
was introduced in ES6 changes. let
is now preferred for variable declaration. It's no surprise as it comes as an improvement to var
declarations. It also solves the problem with var
that we just saw. let
is blocked scoped, a block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block. So a variable declared in a block with let is only available for use within that block. Let me explain this with an example:
let name = 'Akash Kumar Singh'
let age = 22;
if(age>18){
let college = "Dayananda Sagar University";
}
console.log(college); //college is not defined
let
cannot be redeclared unlike var but we can update the value
let name = "Akash"
name = "Akash Kumar Singh" // Allowed
let company = "xyz"
let company = "abc" //Uncaught SyntaxError: redeclaration of let company
Hoisting of let
Just like var
, let
declarations are hoisted to the top. Unlike var
which is initialized as undefined
, the let
the keyword is not initialized. So if you try to use a let
variable before the declaration, you'll get a Reference Error
.
Introduction to const
Variables declared with the const maintain constant values. const
declarations share some similarities with let
declarations i.e. const
is blocked scope. The only difference between let and const is that variable const
variables cannot update values whereas let
variables can update values.
const cannot be updated or re-declared
This means that the value of a variable declared with const
remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const
, we can neither do this:
const greeting = "say Hi";
greeting = "say Hello instead";// error: Assignment to constant variable.
nor this:
const greeting = "say Hi";
const greeting = "say Hello instead";// error: Identifier 'greeting' has already been declared
Every const
declaration, therefore, must be initialized at the time of declaration.
This behaviour is somehow different when it comes to objects declared with const
. While a const
object cannot be updated, the properties of this object can be updated. Therefore, if we declare a const
object as this:
const greeting = {
message: "say Hi",
times: 4
}
while we cannot do this:
greeting = {
words: "Hello",
number: "five"
} // error: Assignment to constant variable.
we can do this:
greeting.message = "say Hello instead";
This will update the value of greeting.message
without returning errors.
Hoisting of const
Just like let
, const
declarations are hoisted to the top but are not initialized.
Important Tips while working with var
, let
& const
Always use
const
when you don't want to change the value.Use
let
when you want to change the value.Name all variables differently.
Define all variables at top of the scope.
( Above all Tips was taught to me by my teacher Tanay Bhaiya π)
Conclusion
A very basic understanding we can get from the above information is that var
is function scope while let
& const
are blocked scope. Always use const
or let
while creating variables in Javascript.