I have read my blog about the var and let. What I see is this.
var is a function or global scope variable depend on where it is defined.
where
let is block scope variable
So in lots of articles, I see they recommend to use let instead of var. I understand that because it eliminated the conflict of the scope of a variable.
So I want to ask where to use let and where to use var? If possible please provide any relevant link for that. If I go with recommendation than I have to use let everywhere.
What I understand is this.
let should be used in for loop as it creates its own lexical scope.
for(let i =0;i<5;i++){
setTimeout(function(){
console.log(i);
},100);
}
So in this case because of let, we will able to print 0,1,2,3,4, but if we have used var it would have print 5 time 5.
Also, I want to know your suggestion on what should be used in function scope and global scope?
let say, I have file index.js
var first = 1; // what should be used here and why
function function1(){
var first = 1; // what should be use here and why `let or var`
var first1 = 2; // what should be use here and why `let or var`
for(let i=0;i<2;i++){
console.log(i);
}
Also, I fill let is more than a variable, I create its own lexical scope, there would be more manipulation under the hood like creating IIFE sort of thing.
What I understand is that we should use function and global scope as var and let as only block scope? Please provide any recommended link which describes what is better where and why?
Thanks.
It's mostly right to only use let these days.
In almost all situations, let is a better or at least equivalent to var considering that leaky declarations make you write error prone code. Avoid using var.
Look at this code:
for(var i = 0; i < 6; i++) {
document.getElementById('my-element' + i)
.addEventListener('click', function() { alert(i) })
}
contrary to this code:
for(let i = 0; i < 6; i++) {
document.getElementById('my-element' + i)
.addEventListener('click', function() { alert(i) })
}
The first one makes a closure which catches i, defined by var, while the other one makes i different values. The first example makes every callback alert 6, since they are all pointing to the same object. However, the let in the second example makes a new block scope every time it iterates. This solves a very common pitfall in javascript.
In most situations, if you need to use var's scope to achieve something not available using let, it's almost always a sign that's something is wrong.
Also, don't rely on var's variable hoisting. If you are using a variable you didn't declare before, it becomes error prone.
Mostly, try to follow on the style guide you follow. If you don't have a special style guide you follow, try the AirBnB's: https://github.com/airbnb/javascript
The "never use var and use let" thing is mentioned here: https://github.com/airbnb/javascript#variables
let and var
You should use var, when you wan to define a variable globally, or locally to an entire function regardless of block scope. Variables assigned with the var keyword have functional scope. The variable isn’t accessible outside of the function.
And, you should use let to declare variables that are limited in scope to the block, statement, or expression on which it is used. When used inside a block, let limits the variable's scope to that block.
Variables assigned with let are very similar to those defined with var. The major difference is scope. This has been referenced above. Variables assigned with let have block scope. This means the variable can be seen within that block and any sub-blocks. Variables assigned with var have functional scope and ignore block scoping rules. Variables assigned with let can not be redeclared, they can only be reassigned.
According to this article, Only use the let keyword when you know that a variable will have a dynamic value. You probably don’t need to use var anymore
Clearly, you know the difference between let and var, and your question is WHERE TO USE WHICH?
First of all, if you are seeking for a better performance, use let wherever you are able to. However, you have to be aware that some old browsers may not be able to handle the let.
Second, I think the best and shortest answer to your question is " use let as long as you can, and if you couldn't then use var".
If you study the differences between let and var deeply, you can figure out where you should use var instead of let, I recommend you to read this article.
Related
Why javascript do hoist on let and const variables and we can't reach them until the initialization and in this way, end temporal dead zone. Is there a particular benefit for this behavior? why js doesn't leave those without any hositing on those?
Because when you shadow a variable, it would be unclear to which variable an identifier would refer in the temporal dead zone, especially as variables declared with var are hoisted too. As such let and const are consistent with var as they are also hoisted, but they're more restrictive in situations where var has shown confusing behavior.
let val = "a";
{
console.log(val);
let val = "b";
}
Programming languages generally have a tradition like variables should be defined at the top. Behind the scenes JS is a part of this tradition too. It hoists var to the top and sets it to undefined until it's defined. This behaviour might lead unwanted consequences because JS will attempt like it's just a normal variable and try to do something with that undefined however since there is nothing you will get an error. So they introduced let and const keywords to prevent this bad behaviour and said these are also hoists and we set them to uninitiliazedand you can't use them until they're assigned to something because that has no meaning, why would you want to use a variable before it assigned to something?
wall it makes things more clear
-sometimes you have to declare the same name of variable multiple times and you don't want to mix up their values
-when you use var it declares on a global scope and after function runs successfully it doesn't clear meemory it stay there in this case if you have many many variables that require too much memory is going to affect on your app performans
in your case:-
let val = "a"; // this let have globle scope
{
console.log(val);
let val = "b"; // this let have local scope that going to be clear from memory when this brakets endes
}
Conclusion:-
var is a global scope
let & const are BLOCK scope that going to be clear after brackets ended
Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?
var is allow duplicate declaration
xx=1;
xx=2;
console.log(xx+xx);//4
var xx=1;
var xx=2;
console.log(xx+xx);//4
But let and const does not allow duplicate deceleration
const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",
let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",
I saw something about that in here like,
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.
But I want to know Why let and const doesn't allow re-declaration? and why var does? and How JavaScript handle these three type of deceleration ?
var
The var keyword was the only way to define variables until 2016*.
No matter where you write var x, the variable x is treated as if it were declared at the top of the enclosing scope (scope for var is "a function").
All declarations of the variable within the same scope are effectively talking about the same variable.
Here is an example... you might think that within the function we overwrite the outer name with fenton, and add Fenton to the inner variable...
var name = 'Ramesh';
function myFunc() {
name = 'fenton';
var name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
In fact, it works just like this... the outer variable is not affected by the inner variable thanks to hoisting.
var name = 'Ramesh';
function myFunc() {
var name;
name = 'fenton';
name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
Actually, you could also declare them implicitly by not using the var keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.
let and const
Both let and const are block-scoped, not function-scoped. This makes them work like variables in most other C-like languages. It turns out this is just less confusing than function-scoped variables.
They are also both "more disciplined". They should be declared just once within a block.
The const keyword also disallows subsequent assignments - so you have to declare it with an assignment (i.e. you can't just write const x, you have to write const x = 'Fenton') - and you can't assign another value later.
Some people think this makes the value immutable, but this is a mistake as the value can mutate, as shown below:
const x = [];
// I can mutate even though I can't re-assign
x.push('Fenton');
// x is now ['Fenton']
Why Does it Matter?
If you want to avoid some of the more confusing aspects of var, such as multiple declarations all contributing to the same hoisted variable, and function-scope, you should use the newer const and let keywords.
I recommend using const as your default keyword, and upgrade it to let only in cases where you choose to allow re-assignment.
Unlike var, let is an ES2015 specification. The specification says:
Redeclaring the same variable within the same function or block scope raises a SyntaxError.
This is to improve scoping over vanilla var.
why does const and let not allow duplicate declaration?
There's a big difference between how c# or java (for example) handle duplicate variable names, where name collision returns a compilation error, and how it works in an interpreted language like js. Please, check the snippet below: The value of i isn't duplicated? Not really, still, in the function and block context the same variable name is referred as two different variables, depending on where those are declared.
function checkLetDuplication() {
let i = 'function scope';
for ( let i = 0 ; i < 3 ; i++ )
{
console.log('(for statement scope): inside the for loop i, equals: ', i);
}
console.log('("checkLetDuplication" function scope): outside the for loop i , equals: ', i);
}
checkLetDuplication();
Assuming you want to know whether this behavior is as per spec, check this 13.3.2
Within the scope of any VariableEnvironment a common BindingIdentifier
may appear in more than one VariableDeclaration but those declarations
collective define only one variable.
let and const are the recent editions, while var is probably as old as Javascript itself.
In old days Javascript code-base didn't used to be too big to bother about programming mistakes and most probably focus was to ensure that instead of reporting the error of re-declaration of variable JS engine should handle it.
I understand that it's not necessary to initialize variables, but what are the benefits of doing so? It doesn't effect the scope of the variable nor the data type. The only reasons I could find were:
Avoid resulting in "undefined"
Explicitly show what the variable is intended for i.e. let myArray = [];
How you define the variable does actually affect the scope of the variable.
There is a big difference between these statements as far as scope, and also as far as mutability for const:
x = 1;
var x = 1;
let x = 1;
const x = 1;
For instance, the first line will create a global variable, the second will create a function scoped variable, and the third line will create a block scoped variable.
Another difference is the concept of "hoisting". let and const do not "hoist".
Initializing variables provides an idea of the intended use (and intended data type).
https://www.w3schools.com/js/js_best_practices.asp
Why does var allow duplicate declaration but why does const and let not allow duplicate declaration?
var is allow duplicate declaration
xx=1;
xx=2;
console.log(xx+xx);//4
var xx=1;
var xx=2;
console.log(xx+xx);//4
But let and const does not allow duplicate deceleration
const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",
let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",
I saw something about that in here like,
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.
But I want to know Why let and const doesn't allow re-declaration? and why var does? and How JavaScript handle these three type of deceleration ?
var
The var keyword was the only way to define variables until 2016*.
No matter where you write var x, the variable x is treated as if it were declared at the top of the enclosing scope (scope for var is "a function").
All declarations of the variable within the same scope are effectively talking about the same variable.
Here is an example... you might think that within the function we overwrite the outer name with fenton, and add Fenton to the inner variable...
var name = 'Ramesh';
function myFunc() {
name = 'fenton';
var name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
In fact, it works just like this... the outer variable is not affected by the inner variable thanks to hoisting.
var name = 'Ramesh';
function myFunc() {
var name;
name = 'fenton';
name = 'Fenton';
alert(name);
}
myFunc();
alert(name);
Actually, you could also declare them implicitly by not using the var keyword at all, in which case they would be added to the global scope. Subtle bugs were often tracked to this.
let and const
Both let and const are block-scoped, not function-scoped. This makes them work like variables in most other C-like languages. It turns out this is just less confusing than function-scoped variables.
They are also both "more disciplined". They should be declared just once within a block.
The const keyword also disallows subsequent assignments - so you have to declare it with an assignment (i.e. you can't just write const x, you have to write const x = 'Fenton') - and you can't assign another value later.
Some people think this makes the value immutable, but this is a mistake as the value can mutate, as shown below:
const x = [];
// I can mutate even though I can't re-assign
x.push('Fenton');
// x is now ['Fenton']
Why Does it Matter?
If you want to avoid some of the more confusing aspects of var, such as multiple declarations all contributing to the same hoisted variable, and function-scope, you should use the newer const and let keywords.
I recommend using const as your default keyword, and upgrade it to let only in cases where you choose to allow re-assignment.
Unlike var, let is an ES2015 specification. The specification says:
Redeclaring the same variable within the same function or block scope raises a SyntaxError.
This is to improve scoping over vanilla var.
why does const and let not allow duplicate declaration?
There's a big difference between how c# or java (for example) handle duplicate variable names, where name collision returns a compilation error, and how it works in an interpreted language like js. Please, check the snippet below: The value of i isn't duplicated? Not really, still, in the function and block context the same variable name is referred as two different variables, depending on where those are declared.
function checkLetDuplication() {
let i = 'function scope';
for ( let i = 0 ; i < 3 ; i++ )
{
console.log('(for statement scope): inside the for loop i, equals: ', i);
}
console.log('("checkLetDuplication" function scope): outside the for loop i , equals: ', i);
}
checkLetDuplication();
Assuming you want to know whether this behavior is as per spec, check this 13.3.2
Within the scope of any VariableEnvironment a common BindingIdentifier
may appear in more than one VariableDeclaration but those declarations
collective define only one variable.
let and const are the recent editions, while var is probably as old as Javascript itself.
In old days Javascript code-base didn't used to be too big to bother about programming mistakes and most probably focus was to ensure that instead of reporting the error of re-declaration of variable JS engine should handle it.
A while ago, I read some article about using let and var in JavaScript and they're saying that a variable you declare using "var" keyword (even in for loop) works only within it's function, so why is it possible to make multiple for loops in one function, each of them look like : for (var i = 0; i < array.length; i++);
and JavaScript has no problem with "redeclaring" the i variable? Thanks :)
JS has a special case for var as it allows hoisting, which means multiple declaration of the same variables is allowed and they got moved to the enclosing functional scope. However they are still the same variable. Consider the following code:
function foo(){
for(var i=0; i<3; i++){
console.log("x");
}
for(var i;i<6;i++){
console.log("y");
}
}
foo()
Notice there is no initialization of i in the second loop, but it will execute fine and produce 3 x and 3 y. It used to be a problem with old browsers, but new browser simply allows it with no error given.
A seemingly small question with a complex answer. var is the old method declaration. You can declare it anywhere and as many times as you want. JavaScript will not care. All declared variables are available immediately, because declaration gets moved up to the very beginning of the function's code. This is known as hoisting.
let is the new way of declaring variables. const exists, but we're not interested in that right now. let is block scoped. The rules behind let and scoping can be confusing, but it's advantageous to learn/understand. It is the future of JavaScript. I thoroughly talk about it in my blog post, here.
let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var.
var is rather a keyword which defines a variable globally regardless of block scope.
ES6 introduced the 'let' keyword to tackle this issue only. It allows a variable to be bound to its scope within a function so that you cannot re-declare it outside preventing hoisting issues. Example -
for(var i=0; i<5; i++) {
console.log(i);
}
console.log(i);
Here the output will be - 0 1 2 3 4 5
Instead of 5 we must get 'Uncaught Reference Error' since variable i should be accessible only within the function. Because of Hoisting in JavaScript, all the variables and function names are stored to one place before execution. So the code actually looks like the following -
var i;
for(i=0; i<5; i++) {
console.log(i);
}
console.log(i);
This is resolved if you use the let keyword.