Search This Blog

Thursday, March 1, 2018

Javascript var vs let vs const & Hoisting

In JavaScript we can define variable with var .
With ES6 we can also define variable with let & const.

There is subtle difference in scope of variable defined with var & let.
There is further difference due to hoisting behaviour for var in javascript.

declaration of variable using var keyword:
var keyword is used in JavaScript to declare a variable along with
optional initialization of variable.
e.g.
var x=10;
or
var t;

The scope of a JavaScript variable declared with var is its current
execution context while the scope of a JavaScript variable declared
outside the function is global.

Code:
function varScopeDemo(){
var x ='initial';
console.log(x);

if(1==1)
{
var x='first';
console.log(x);
}
console.log(x);
}

Output:

initial
first
first

This behavior is specific to the var keyword in JavaScript,
where variables declared using var are function-scoped
rather than block-scoped.
This means that variables declared with var are accessible throughout
the entire function, regardless of where they are declared within the
function.

Now lets replace var in our function with 'let'

Code:

function letScopeDemo(){
let x ='initial';

console.log(x);
if(1==1){
let x='first';
console.log(x);
}
console.log(x);
}

Output:
initial
first
initial

'let' create a variable with the scope limited to the block on which it is used
that is why console.log outside if block has value assigned before if block &
not from if block initialization.

This behavior is specific to the let keyword in JavaScript,
which introduces block-scoped variables. Variables declared
using let are only accessible within the block in which they
are declared or in nested blocks. They do not override variables
with the same name declared in outer scopes.

Now lets move to 'const'.

Code:
function constScopeDemo(){
const x ='initial';

console.log(x);
if(1==1){
const x='first';
console.log(x);
}
console.log(x);
}

Output:
initial
first
initial

in terms of scope 'const' are same as 'let'


Reassignment to constant variable:

Now let us try another code snippet

Code:

function constScopeDemo(){
const x ='initial';

console.log(x);
if(1==1){
x='first';
console.log(x);
}
console.log(x);
}

Output:
Uncaught TypeError: Assignment to constant variable.

Here when we try to execute 'constScopeDemo' function we get an error because
'const' statement can assign value once and they cannot be reassigned.


we need to assign value to variable defined with const else it result in an
error.below line when execute result in error

Code:
const name;

Output:
Missing initializer in const declaration.


Redeclaration of variable in same scope using var:
Consider following code snippet

Code:
function varScopeDemo() {
var x = "initial"; // Declare and initialize x as "initial"
var x = "second"; // Redeclare x as "second"
console.log(x); // Output: second
}
Output:
second

Explanation:
In JavaScript, using the var keyword allows you to redeclare variables
within the same scope without causing an error. However, it's important
to note that redeclaring a variable with var effectively overrides the
previous declaration.

Redeclartion of variable in same scoper using let.

Code:
function letScopeDemo() {
let x = "initial";
let x = "second";
console.log(x);
}

Output:
Identifier 'x' has already been declared

Explanation:
In JavaScript, when using the let keyword to declare variables,
redeclaring a variable with the same name in the same block scope
results in a syntax error.

Global Declaration of variable:
Consider following code snippet

Code:
t=10
console.log(t)
Output:
10

Explanation:
t = 10; assigns the value 10 to t.
Since t is not explicitly declared using var, let, or const,
it becomes a global variable by default.

JavaScript will treat t as a global variable.if you're in a browser
environment; In Node.js, it would be a module-level variable.

Hoisting in javascript:

Hoisting is JavaScript's default behavior of moving all declarations to the
top of the current scope.JavaScript only hoists declarations, not
initializations.

Consider following code snippet

Code:
var x = 8;
console.log(x + " " + y + " " + t);
var y = 64;

Output:
Uncaught ReferenceError: t is not defined

Explanation:
here t is neither declared using var nor by let or const.nor is it a global
variable.

Now lets modify this snippet little bit

Code:
var x = 8;
console.log(x + " " + y );
var y = 64;

Output:
8 undefined

Here y is defined after its use in console.log but due to Hoisting
its declaration is taken up in snippet so when we go to console.log
statement variable is defined but it has value undefined because
initialization is not hoisted.

Lets check hoisting behavior with 'let',in following code snippet
again 'y' is declared after use.

Code:
let x = 8;
console.log(x + " " + y );
let y = 64;


Output:
Uncaught ReferenceError: y is not defined

Here we not getting 'y' with undefined value as variable 'y' is not yet defined.
Hoisting does not happen when variable defined with let & const.

Hoisting & global variable:
Consider following code snippet

Code:
console.log(t)
t=10

Explanation:
Even if t is global variable,we can't use it before declaration.Hoisting
does not happen here.

Output:
ReferenceError: t is not defined


Mixing var & let
Consider code snippet below

Code:
let count = 40;
var count = 30;

Output:
Identifier 'count' has already been declared

This happen irrespective of let comes first or var comes first.

Closure :
Consider code snippet below

Code:
for (var i = 0; i < 5; ++i) {
console.log('log:' + i);
setTimeout(function () {
console.log(i);
}, 100);
}

Output:
5 5 5 5 5

on contratory

Code:
for (let i = 0; i < 5; ++i) {
console.log('log:' + i);
setTimeout(function () {
console.log(i);
}, 100);
}

Output:0 1 2 3 4

Explanation:
There is difference in behavior between let & var because ,
the let in the loop can re-binds it to each iteration of the loop,
making sure to re-assign it the value from the end of the previous
loop iteration.

No comments:

Post a Comment