Let vs Var vs Const in JavaScript
let vs var vs const are the things that always keeps us in amusement
that on what time which one to use. So here in this post all your doubt’s will
get clear on where you need to use any of these and what are their advantages.
As per the ES6 which came in 2015 there are new ways to create a variable in
JavaScript with “let” and “const”. Moreover, to understand this we will firstly
go through topics like function vs block scope, variable hoisting, and
immutability.
Variable Declaration vs Initialization
var x
Above we create a new identifier called ‘x’. In JavaScript, variables
are by default initialized with the value of undefined whenever they are
created. So, if we try to log the ‘x’variable, we’ll get undefined.
var x
console.log(x) // var x is undefined
In contrast to variable declaration, variable initialization is done
whenever you assign a value to a variable either at the time of declaration or
after that.
var x;
console.log(x) // var x is undefined
x= 'initialization';
So here we have assigned the value to the declared variable ‘x’ which is
called initialization.
Scope
As the name suggest scope is a block so, it means where variables and
functions are accessible inside of your program. JavaScript provide us mainly two
kinds of scope –
1.
Global
scope.
2.
Function
scope.
If any variable created with var, then that variable is said to be
“scoped” to the function it was created in and it will be only accessible
inside of that function or any of the nested functions inside it.
For Example -
function getName () {
var name = “John”;
return name
}
getName()
console.log(name)
Output -VM81:8 Uncaught
Reference Error: name is not defined
In the mentioned above example, we are trying to access a variable
"name" outside of the function it was declared. Since “name” is
inside ofgetName() function so it is in the scope of it, and therefore it is
only accessible inside of getName() itself or any nested functions inside of
getName() function.
Now that we became familiar with variable declarations, initializations,
and scope, lets look at hoisting.
function getName (firstName, dislastName) {
var
names = undefined;
var
firstName = undefined
var
lastName = undefined
names
= []
for
(var j = 0; j < 2; j++) {
firstName = "John"
lastName = "Doe"
names.push(firstName);
names.push(lastName);
}
console.log(j)
console.log(firstName);
console.log(lastName)
return names;
}
Simple thing
here to note is that all the variable declarations were assigned a default
value of “undefined”. That’s why if you try to access any of those variables even before
they were declared, you’ll definitely just get undefined.
Difference
between var, let, and const?
1.
let and var
Let is block
scoped instead of being function scoped, which also means that a variable
created with the let keyword is always accessible inside the “block” in which
it was created in and any of nested blocks that were a part of it. Here
“block”, means {} and anything surrounding it.For example, in a while loop or
an if, else if statement.
function
getName (firstName, lastName) {
let names = []
for (let j = 0; j < 2; j++) {
let firstName = "John"
let lastName = "Doe"
names.push(firstName);
names.push(lastName);
}
console.log(j)
console.log(firstName);
console.log(lastName)
return names;
}
getName("John",
"Doe");// ❌Reference Error
occur: ‘j’ is not defined
We got “Reference Error: j is not defined”. What this means is that
variables declared with let are block scoped, not function scoped. So, while
trying to access j (or any declarations inside the function scope) outside of
the “block” they were declared in will be going to give us a reference error.
The next difference of let has to do with hoisting. We have already seen
the example by console logging a variable even before it was declared, and we
got undefined as a result. So it’s a simple concept that if you try to access
any variable declared with let before it is declared then instead of getting
undefined (like we get it with those variables declared with var), one will always
get a “Reference Error”.
2.
let
VS const
Since we have seen and understood the basic difference between var and
let, lets dive into const? Const is almost exactly similar as let. However, as
the name itself suggests "const", the only difference is that once a
value has been being assigned to a variable using const, one cannot reassign
any new value to it.
let name = 'John'
const any = 'anything'
name = 'John Doe' // ✅
any = '@anything' // ❌ TypeError: Assignment to constant variable.
What we understood from the above example is that variables declared with
let can be re-assigned, but variables declared with const can’t be.
Awesome, so anytime you want a variable that you don’t want to make
changes in its value, you can declare it with const. In other words if we want
to put it like, a variable is declared with const not always mean that it’s
immutable, it means the value can’t be re-assigned to it. Here’s a good
example.
const objectPerson = {
name: 'John Doe'
}
objectPerson.name = 'John Doe West' // ✅
objectPerson = {} // ❌ Assignment to constant variable.
We can always change a property on an object at will and that doesn't
mean we are reassigning its value, so even if an object is declared with const
keyword, it doesn’t mean you can’t mutate any of its properties. So, simply it refers
that you can’t reassign it to any new value.
NOTE –
1.
var – function scope
accessing
a variable before it's declared will give undefined
2.
let – block scoped
“Reference
Error” when accessing a variable before it's declared
3.
const - block scoped
“Reference
Error” when accessing a variable before it’s declared can't be reassigned
Comments
Post a Comment