Log in

View Full Version : What is the main difference between var and let in JavaScript?



dennis123
11-15-2017, 06:48 AM
What is the main difference between var and let in JavaScript?

davidsmith21
11-16-2017, 05:38 AM
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.

Lebar.123
11-16-2017, 10:39 AM
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.

DanielDP
11-22-2017, 04:40 AM
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.

sanjalisharma89
11-27-2017, 01:11 AM
Scoping makes the difference. var's scope is function level but let is scoped in its enclosing block, that is ({}).

Drasti_Chavda
04-02-2019, 01:41 AM
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

Sherin
06-27-2019, 02:00 AM
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

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

2)var

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.