Latest Posts

Tuesday, July 11, 2017

Javascript : Var and Let





-->
var let
The scope of a variable defined with var is function scope or
Declared outside any function, global.
The scope of a variable defined with let is block scope.
Examples
function varandlet() {
var i = 5;
}
console.log(i);
VM131:1 Uncaught ReferenceError: i is not defined at
function varandlet() {
let i = 5;
}
console.log(i);
VM131:1 Uncaught ReferenceError: i is not defined at
function varandlet() {
For(var i=0;i<10 br="" i=""> console.log(i);
}

Varandlet(); // Output = 10; No error here
function varandlet() {
For(let i=0;i<10 br="" i=""> console.log(i);
}

Varandlet();

VM350:1 Uncaught ReferenceError: i is not defined at varandlet (:1:62)
at :1:1
******** LET has block level scope.
{
var o = p = 10;
}
console.log( o);
console.log( p);
// Output
// O = 10
// P = 10
{
let o = p = 10;
}
console.log( o);
console.log( p);
// Output
// Error O is not defined
// P = 10 // In this case P becomes global variable
for (var i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i); // output '5' 5 times
}, 100);
}

//Output will be five times 5

The settimeout function works in asynchronous way.
Closure in Loop

for (let i = 0; i < 5; ++i) {
SetTimeout(function () {
console.log(i); // output '5' 5 times
}, 100);
}

//Output will be five times 1 2 3 4 5

let in the loop can re-binds it to each iteration of the loop, making sure to re-assign
t the value from the end of the previous loop iteration, so it can be used to
avoid issue with closures.

No comments:

Post a Comment