What is the main difference between var and let in JavaScript?
What is the main difference between var and let in JavaScript?
let enables you to pronounce factors that are restricted in degree to the piece, explanation, or articulation on which it is utilized. This is not at all like the var catchphrase, which characterizes a variable comprehensively, or locally to a whole capacity paying little mind to piece scope. A clarification of why the name "let" was picked can be found here.
The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
Also, variables declared with let are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.
█ Check out our new Online Email Validator @ Zero Bounce
█ Our unique email validation service eliminates high bounce rates.
let creates a variable that is only accessible in the block that surrounds it
var - creates a variable whose scope is accessed through the function that contains it.
Scoping makes the difference. var's scope is function level but let is scoped in its enclosing block, that is ({}).
Var and let both are used for function declaration. The difference between Var and Let is that Var is function scope and Let is the block scope.Variable declared with var is defined throughout the program while Let is not
.NET Developer At iFour Technolab Pvt Ltd
http://www.ifourtechnolab.com/
var and let are both used for function declaration in javascript.
Main difference between them is the scope difference.That is var is function scoped and let is block scoped.
Example::
1)let
2)varCode:for(let i=0;i<10;i++){ console.log(i); //i is visible thus is logged in the console as 0,1,2,....,9 } console.log(i); //throws an error as "i is not defined" because i is not visible
Code:for(var i=0; i<10; i++){ console.log(i); //i is visible thus is logged in the console as 0,1,2,....,9 } console.log(i); //i is visible here too. thus is logged as 10.
Last edited by Sherin; 06-27-2019 at 02:32 AM.
|
Bookmarks