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 10> |
function varandlet() { For(let i=0;i<10 br="" i=""> console.log(i); } Varandlet(); VM350:1 Uncaught ReferenceError: i is not defined at varandlet ( at ******** 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. |
Tuesday, July 11, 2017
Javascript : Var and Let
By
Neeraj Kumar Jha
10:50 PM
distributed system design. MongoDB, ES6, javascript, JScript, Let and var, let Vs var, linux, Modern JScript, nginx server
-->
Labels:
distributed system design. MongoDB,
ES6,
javascript,
JScript,
Let and var,
let Vs var,
linux,
Modern JScript,
nginx server
Javascript : Var and Let
Reviewed by Neeraj Kumar Jha
on
10:50 PM
Rating: 5
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment