Link to home
Start Free TrialLog in
Avatar of APD Toronto
APD TorontoFlag for Canada

asked on

JavaScript let vs var

Hi Experts

Can anyone please explain to me the difference between var and let, if any.

Thank you!
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Hi
First you must understand the term of the scope and its purpose. So scope in a plain words as I am referring by this scope is "Scope is the set of variables you have access to." More simply scope is a bucket that function, variables, object that we can have or not accessibility. You must have the permission to enter your hand in the bucket and use these all things inside.
Usually the scopes in javascript works like the Russian dolls User generated image.A small bucket (or doll) contained inside in a bigger one a so on.
The small bucket can have access to a variables in a bigger bucket but  not inside in a smaller.

The var declares variables in global or (bigger) scope (bucket or doll) and the let declares variables in a block of scope (bucket or doll).The let declaring is more strict. You can var-let ES6
From here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let
let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

In a nutshell
  * var scope works back to the nearest function
  * let works back to the nearest enclosing block
Consider the following coe
<script>
function test()
{
	for(var i = 0; i < 10; i++) {
	 // p accessible anywhere in function
	 var p = 10
	 // x only in for
	 let x = i * i;
	 console.log(i + ' : ' + x);
  }
  console.log(i);
  console.log(p);
  console.log(x);
}
test();
</script>

Open in new window

Avatar of APD Toronto

ASKER

Thanks guys...

Leonidas- I do have a Russian doll myself - my Wife!

By my understanding, the only difference is:
//Example 1
let x = 1;
if (x == 1){
   let x = 2;
   console.log(x); //Outputs 2
}
console.log(x); //Outputs 1

//Example 1
var x = 1;
if (x == 1){
   x = 2;
   console.log(x); //Outputs 2
}
console.log(x); //Outputs 2

Open in new window


If I'm correct, then when would you use Example 1?
SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial