Reputation: 71
I looked at tons of questions/answers on the "no var" topic but I'm still confused
"no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it)
I get this, but what does "no var" do if it does find something? e.g if you want to change an existing variable or binding, do you use var/let again or is it OK if you don't? Is there a difference?
Upvotes: 6
Views: 8992
Reputation: 1
I've just faced this situation that lead me to this post, I think it's a good example:
let requestViaCEP = function (cep) {
callbackRequestViaCEP = function (resultadoCEP) {
responseViaCEP = resultadoCEP;
}
return new Promise ((resolve, reject) => {
$.getScript("https://viacep.com.br/ws/" + cep + "/json/?callback=callbackRequestViaCEP", function(resultadoCEP){
// console.dir(CEP.responseViaCEP)
resolve(resultadoCEP)
})
}
).then((value) => { return value },
(error) => { return new Error('CEP não encontrado.') } )
}
The 'callbackRequestViaCEP' function is only acessible when I declare it without using let, var or const. Now I know that it happens because once you don't use them, the variable goes to the global escope. I'm not sure if this is the best strategy, if not I hope you guys let me know, but for now it's the only way I found to make it work..
By the way, this is the first time I see it happening, found it pretty cool :)
Upvotes: 0
Reputation: 16291
The short answer is no, not in modern JavaScript.
A feature of the rough-and-ready design of JavaScript in the past is that variables were automatically created, whether you meant to or not.
This means that the following code:
apple=3;
Apple=apple+4;
alert(apple);
would lead to two variable being created (JavaScript, is, of course, case sensitive), and you would have a logical error in your code.
In modern code, you should begin with the 'use strict'
directive, which would disallow undeclared variables:
'use strict';
var apple=3;
Apple=apple+4; // error: undeclared Apple
alert(apple);
'use strict'
helps to close a gap which leads to sloppy and hard to manage code. It would raise an error when trying to assign to an undeclared variable.
The var
keyword serves two roles. First, it declares the variable, thus informing the JavaScript interpreter that it’s intentional. Second, it also sets the scope of the variable — the scope will be that of the containing environment, generally a function, where the variable was declared.
Even more modern JavaScript has added const
, which locks a value of what would otherwise be a variable (a read-only variable), and let
which give a variable an even more limited scope.
You should normally use the 'use strict'
directive, which will enforce a good habit. In any case, you should always declare your variables/constants as part of your careful code design.
In my opinion, anybody who finds declaring variables too arduous is off to a bad start, and probably shouldn’t be writing JavaScript.
Upvotes: 2
Reputation: 16515
If no var
, let
or const
statement is used like:
x = 100;
than the variable gets assigned to the global scope, or reassigned where it is found in the scope, what very often is not the desired behavior, since that leads to cluttering in the scope, or variable overriding, so strange bugs.
To reassign a variable wherever it is found in the scope, just us the same method as above:
x = 101;
If you have something like this:
//global scope
var z = 40;
(function () {
//scope »level 1«
var x = 100;
//implicitly declared in global scope
y = 300;
z += 1;
console.log(z); //41
(function () {
//scope »level 2«
x = 101;
z += 1;
})();
console.log(x) // 101;
console.log(y) // 300;
console.log(z) // 42;
})();
console.log(x) // undefined;
console.log(y) // 300;
console.log(z) // 42;
A basic example of using the scope chain in a useful way:
//create a »working scope«
//to prevent cluttering the global
(function () {
var getID = (function () {
//hide the id variable in child scope
//to prevent it from modification
var id = 0;
return function () {
//modify and return values
//from this scope
id += 1;
return id;
}
})();
//that doen't make much sense,
//but is also a example of using a
//working scope
var usedIds = Array.prototype.slice
.call(document.querySelectorAll('.a-class'))
.map(function (node) {
var id = 'my-id-' + getID();
node.id = id;
return id;
});
// export/expose variables to the global scope explicitly
window.globallyNeeded = usedIds;
})();
Upvotes: 12
Reputation: 1362
You only use var
or let
if you initialize a variable at a scope at your choice. But keep in mind, that the let
keyword for variable initialization only works for ECMAScript 2016 and later. Also, the const
keyword. The difference between let
and const
is, that the first one is variable (its value can be changed) and that the second one is a constant (its value can't be changed, it's a fix value).
Also, the let
keyword has a more strictly scope defintion. That means, that the let
keyword is block scope specific. Only inner blocks can read the outer let
variable. But if you define a let
variable inside e. g. an while block, it does not exist outside the loop.
Upvotes: 0