Why is a variable available outside it's code block? [duplicate] - javascript

This question already has answers here:
Why the for loop counter doesn't get destroyed after exiting the loop in javascript?
(3 answers)
Closed 9 years ago.
I ran into this little gem 5 minutes ago. I have been playing with JavaScript for a long while now and, since I follow best practice, I've never met such case, nor understand why it works while I supposed it shouldn't :
for (var i=0; i<10; i++){
// ... something
}
console.log("i=", i);
will output 10
How is i available outside the for block? I always thought the declaration part was to have a local variable only available within that block.

I always thought the declaration part was to have a local variable only available within that block.
Nope, not in JavaScript.
JavaScript loops (and most blocks in general) have no block scoping (until then next version rolls out with let.)
There are only two places where JavaScript does block scope at the moment and that's with clauses (you shouldn't use those anyway) and catch clauses.
Instead, JavaScript relies mostly on function scoping - variables declared in a function are local to that function.

In this case the declaration of i is outside the code block. In any case, Javascript doesn't have a block-level scope. Variables are either global, or within the scope of a function.

Because that's equivalent to:
var i=0;
while (i<10){
// ... something
i++;
}
In fact, loops do not even create their own scope at all:
var x = 0;
while (x < 10) {
x++;
var i = 5;
}
i; // 5

i will be available below where you have defined it, unless you close off the scope, like:
(function(){
for(var i=0; i<10; i++){
}
})();
console.log(i); // undefined
This should not matter though, because as long as you are using other loops below you can use the same increment variable (with the exception of nested loops), which will overwrite the other one. A problem could arise when you have a loop where you forget to use the keyword var. Always use var would be my recommendation. A closure is not usually necessary.
In a nested loop you can use the same increment variables again like:
for(var i=0; i<10; i++){
for(var n=2; n<44; n+=2){
}
}
// feel free to use `i` and `n` again
Or loops like this:
var ar1 = ['a', 'b', 'c'];
for(var i=0,l=ar1.length,n=0; i<l; i++,n+=2){
}
// feel free to use `i`, `l`, and `n` again
Personally, I find it a best practice to reserve vars i, n, c, and q for counters and l for length. Then I don't use them elsewhere, besides in loops.

In javascript, there's no "block scope", but "function scope". It means that, as soon as your variables are defined inside a function, they'll remain alive from the point that they're declared until the end of that function, whether inside or out side a block.
Here is the test case for js variable scope (from Secrets of the Javascript Ninja, sections 3.2.1 Scoping and functions)
Test case:
function outer(){
var a = 1;
function inner(){ /* does nothing */ }
var b = 2;
if (a == 1) {
var c = 3;
}
}
outer();
Result:

Related

Must we include Let keyword in javaScript For Loops?

I am learning about For Looops and I find that the following two pieces of code work just the same.
Code 1:
for (let i=0 ; i<bobsFollowers.length; i++){
for ( let j=0; j<tinasFollowers.length; j++){
if (bobsFollowers[i] === tinasFollowers[j]){
mutualFollowers.push(tinasFollowers[i]);
}
}
}
console.log(mutualFollowers);
Code 2
for (i=0 ; i<bobsFollowers.length; i++){
for ( j=0; j<tinasFollowers.length; j++){
if (bobsFollowers[i] === tinasFollowers[j]){
mutualFollowers.push(tinasFollowers[i]);
}
}
}
console.log(mutualFollowers);
You can globally access the variable if you do not include let keyword
for (let i = 0; i < 3; i++) {
console.log(i);
}
for (j = 0; j < 3; j++) {
console.log(j);
}
console.log('j ', j); // accesible
console.log('i ', i); // inaccesible
Yes, if you do not specifically use the let keyword in a for, for...of or for...in loops etc, they will work the same as when you use the let keyword.
However, when you don't explicitly declare using let keyword, the variable will be declared as a var. let and const are block level variables, but you also need to understand that 'functions are not the only blocks, any { } is basically a block'. i.e. Once declared a 'var' will become a function scoped variable and in case it is not inside a function, and declared outside, then it becomes globally available, which is not such a good thing considering you might have multiple for loops using a variable named 'i' and if you don't use let, it will just keep incrementing the old 'i'. Please see the below two examples to understand what I mean by the above sentence:
const test = function(){
let let1 = 1;
var var1 = 2;
{
let let1 = 9; //This is a block scoped variable limited to this { } block
var var1 = 3; //re-initialization still overrides the original var 1 variable's value because once declared, the var variable is function scoped
console.log(let1); //9 - Block Scoped
console.log(var1); //3 - Function Scoped
}
console.log(let1); //1 - Function Scoped
console.log(var1); //3 - Still Function Scoped, always function scoped
}
test();
What I meant by globally incrementing value of 'i':
for(i=0; i< 2; i++){
console.log('first loop', i)
}
for(i;i< 5; i++){//I am not initializing i to 0, but I'm just trying to show that it is a global variable now.
console.log('second loop', i)
}
for(i; i< 7; i++){ //I am not initializing i to 0, but I'm just trying to show that it is a global variable now.
console.log('third loop', i)
}
Secondly, in ES5, Strict Mode was introduced, which basically is a way you can opt out of writing 'sloppy mode' JS code, and you can use it by specifying 'use strict'; globally or at a function level. And strict mode is used in most companies and developers in their professional code bases.
The point I want to convey with this is that 'Strict Mode' does not allow you to use for loops without declaring the variable, you have to explicitely specify the 'var' or 'let' keywords. Therefore it is always a good practice to declare your variables. You can read more about strict mode here: Strict Mode
Lastly, in the current post ES6 times, using the var keyword to declare variable is not considered as a good practice due to something called as Hoisting, which basically means that before the a var x; is declared, if you try to use it, you still can, however it's value will be 'undefined'. But in case of let you cannot use a variable before you declare it. You can read more about it Here : Hoisting
Also, in case of let if you try to access a variable before it's initialized, it throws you a Reference Error. This is because of a concept called as a 'Temporal Dead Zone'. You can read more about it here: TDZ
'let' is all about lexical scope, by default variables and objects in javascript have a global scope. As other have pointed out, using var will make the scope of variable global so anything can access and modify it.
Another use case for let would be in closures.
This example is from CS50's react native lecture 0 & 1.
Here makeFunctionArray returns an array of functions which print the value of i.
function makeFunctionArray() {
const array = [];
for(var i=0; i<5; i++) {
array.push(function () { console.log(i) });
}
return array;
}
const functionArray = makeFunctionArray();
functionArray[0]();
Now, what do you expect functionArray[0]() to print?
0, right? because we're invoking the function at index zero and it should console log 0.
But it doesn't print 0, instead it prints 5.
This is because 'i' has a global scope and will have a value of 5 when loop terminates.
the function(closure) we're returning from the makeArray function will still have access to 'i' and the value 5 gets wrapped up in it while being returned. so every functionArray[index]() will print 5.
This can be avoided with 'let' if 'i' is a let, its scope will only be the 'for' loop.
At the end of this lecture, this scenario is introduced and answered in next lecture
Yes, you have to. Or the old var
As other responses mention you will populate this variable in a broader scope.
Imagine this situation, You need to create a function that print the first 10 numbers:
function printNumbers(){
for (i=0; i<10; i++) {
console.log(i)
}
}
That's cool. Now you need to invoke this function 12 times, easy right?
function printNumbers(){
for (i=0; i<10; i++) {
console.log(i)
}
}
for (i=0; i<12; i++) {
printNumbers()
}
Well, if you execute this in your google chrome console (don't). You will fry your browsers. Since i will never reach 12 and you will be in an infinite loop.
You can test this safely by changing 12 by 5, you will see that the function only runs 1 time and not 5.
So it is not for your code (only), it is for who is going to use your code in the future. You are leaving a potential big fail in your code. Imagine it is in a library.
You have a good explanation already in StackOverflow about scoping and let here: What's the difference between using "let" and "var"?
Also about scope in general here: What is the scope of variables in JavaScript?
The scope of let is restricted to that block alone. but if you do not specify let keyword it is scoped to the global environment(the global scope of the browser is window object)
{
let a = 1;
b = 2;
}
console.log(a) //error
console.log(b) //2

Javascript, is using the var keyword a best practice? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 7 years ago.
It seems to me that anytime a variable is declared, it should use the var keyword (unless it's specifically trying to access a global variable). Particularly because local variables can be collected when their function exits. But does it make any difference in something like a for loop?
for(var i = 0; i < ...; i++)
Generally, is there any standard best practice about the use of var keyword?
Generally, is there any standard best practice about the use of var keyword?
Yes there is. And that is to use var every time.
But does it make any difference in something like a for loop?
There is no block-scope in javascript yet. So it makes no difference whatsoever. It is same as
var i;
for(i = 0; i < 10; i++) {
// you can access i inside
} // as well as outside the loop
Declaring variables without var keyword throws an error when used in 'use strict'. So it's always better to use var keyword and avoid the ambiguity by attaching a property to window if you want it to be global.
Ah forgot about let keyword, which will make its way in ES6, which allows for a block scope. So it can be written as
for(let i = 0; i < 10; i++){
// i can be accessed here but not outside this block
}
Also it's worth noting is that
MDN: First, strict mode makes it impossible to accidentally create global
variables. In normal JavaScript mistyping a variable in an assignment
creates a new property on the global object and continues to "work"
(although future failure is possible: likely, in modern JavaScript)
which means, that it is considered an accidental mistake if you omit var keyword and omitting it might not work in the future iterations of ECMAScript aka Javascript.
Use var and you'll not pollute global context, your variables will be context-aware and be fail-proof for future versions of javascript, or in MDN's words, modern JavaScript.
In Javascript, the var keyword appears to be optional. This is incorrect.
With var, a variable is created in the current scope. Without it, the variable is attached to the global scope. (This is window in the browser).
You should absolutely use var wherever possible. If you mean to intentionally attach a variable to the window, state that directly:
window.foobar = 'some text';
Declaring a variable in a for-loop is the same as declaring a variable anywhere else.
I doubt you want every loop in your program all trying to use window.i the same time, which is what will happen if you don't use var.
The comments are partially wrong.
Only functions have scope in javascript, so a for loop var has no actual functional difference. Using var in for loops does create the semantic implication that the value shouldn't be used later, though.
for(i = 0; i < 5; i++){}console.log(i);
for(var j = 0; j < 5; j++){}console.log(j);
q = 17
for(var q = 0; q < 5; q++){}console.log(q);
All 3 output 5 but with a var declaration I would not expect a future user of the for loop variable.

Using var when declaring i in a for loop [duplicate]

This question already has answers here:
"var" or no "var" in JavaScript's "for-in" loop?
(10 answers)
Closed 7 years ago.
I've seen Javascript code that has used two different ways of defining a for loop.
for (var i=0;i < x.length; i++)
But it's also been
for (i=0; i < x.length; i++)
The same thing has happened with for-in loops
for (var i in x)
and
for (i in x)
Is there any difference between declaring i as a var and just saying i? Are there advantages of doing one over the other? Is one these right way to do this? From what I can tell, they both act the same, but there has to be some difference.
Note: I'm not asking about the difference between for-in and for (i=0)
Without a var declaration somewhere in a function, references to i will be to the i property of the global object. This risks all sorts of unpredictable behavior if code in the body of the for loop invokes code (say, inside a called method) that also modifies the global i.
Note that declaring var i in the for loop initialization
for (var i = ...)
is equivalent to declaring var i; before the for loop:
var i;
for (i = ...)
In particular, the declaration of i will be hoisted to the top of the enclosing scope.
EDIT: If you enable strict mode, then you must declare your loop variables (all variables, actually). Referencing a variable that has not been declared with a var statement will result in a ReferenceError being thrown (rather than resulting in a global variable coming into existence).
JavaScript is functionally scoped. At least for now, the language does not have block level variables.
When you write for (var i=0; ... ); it is the same as
var i;
for (i=0; ... );
In the absence of "use strict"; variable declaration will be hoisted.
for (i=0; ... ); alone implies that i belongs to the global (top most) object (in browsers it's window)
Intro:
The for statement creates a loop that consists of three optional
expressions
Source: Mozilla JavaScript Docs
Background:
You are referring to initialization, which is an expression or variable declaration. It's almost always used to initialize a counter variable that allows us to iterate through a collection as you've shown.
This expression may optionally declare new variables with the var
keyword. These variables are not local to the loop, i.e. they are in
the same scope the for loop is in. The result of this expression is
discarded.
In JavaScript, variables can hold different data types, and in the case of a counter variable, JavaScript treats the variable as a number.
Answer:
The reason one can optionally declare a new variable (or not at all, as you've highlighted) is due to the nature of the JavaScript programming language. You've hit upon an important aspect of the language that deals with variables and scope.
"To var or not to var"
Please see this other post about using var or not using it at all to understand more...
What is the function of the var keyword and when to use it (or omit it)?
If you say start using "i" without saying "var" first, you should have declared the variable before your for loop.
Like:
var i;
for (i = 0; i < x; i++) {
doSomething();
}
==OR==
for(var i = 0; i < x; i++){
doSomething();
}

Reusing "i" for JavaScript for loops

I recently started using PHP Storm (love it) and noticed that it flags declarations of "var i" in for loops as duplicate in JavaScript. I learned that apparently the scope of that variable exists outside of the loop.
for (var i = 0; i < 10; i++) {
// Do anything
}
console.log(i); // i == 10
When I do my next for loop, should I declare var i again? Or, should I just say i = 0? I know I can do either, but one seems like bad style, the other like bad implementation.
On one hand, you shouldn't re-declare a variable that's in scope, but if I, for instance, delete the first for loop that declares "i", then everything else will break.
JavaScript has only function level scope, no block level scope. So, if a variable is declared anywhere within a function, it will be available for the entire function. So, you don't have to declare it again.
The best practice is to declare all the variables used in the function at the beginning of the function.
For example,
function myFunction() {
console.log(i);
for (var i = 0; i < 10; i++);
console.log(i);
}
myFunction();
Would print,
undefined
10
i is declared in the function, but till the for loop is executed, i is not assigned any value. So, it will have the default value undefined in it.
you need not declare it again. you can simply reassign the value of i for the next loop like
for (i = 0; i < 5; i++)
{
// Do anything
}

JavaScript loop variable scope

Just a quick question about the scoping of JavaScript variables.
Why does the alert() function print the value of i instead of returning undefined?
$(document).ready(function () {
for(var i = 0; i < 10; i += 1){
}
alert("What is 'i'? " + i);
});
I'm fairly new to JS, and in nearly all other languages I've dabbled, a declaration in the scope of the for loop would contain the value to that said loop, but not in this case, why?
i.e. What is 'i'? 10' is printed.
See the MDN for the "initialization parameters" of a for-loop:
An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.
JavaScript didn't have block scope until const and let were introduced, just var which is function scoped. Since the initialization of i is within one function, that variable is accessible anywhere else in that same function.
From MDN:
Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.
The javascript folks are trying to fix this!
EcmaScript6 (aka EcmaScript 2015) is the latest version of javascript that was passed last summer and browsers are just starting to support its features.
One of those features is block-scope local variables with the "let" expression. As of right now (April 2016), most of the current versions of the major browsers support this except Safari. Few mobile browsers support this.
You can read more about it here (in particular, see the section "let-scoped variables in for loops"):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
You can check current browser support here (look for the row Bindings -> let):
https://kangax.github.io/compat-table/es6/
Unlike other languages (for example: Java, C++, C), JavaScript doesn't support block scope. Once you declare a variable in a loop or in a function it's scope is within the function body if you do
for(i=0; i<arr.length; i++) {
var j=0;
// ...
}
here your i becomes a global variable and j become local to the function or script in which the loop is.
for(i=0; i<arr.length; i++) {
var j=0;
// ...
}
it is not correct to state that the above creates a global variable i. I believe you should always use var to declare variables (unless you are intentionally wanting a 'property' rather than a 'variable' -which is pretty unlikely in 99.99% of JS coding scenarios ...)
Omitting var when assigning an initial value to i isn't creating a local or even a global variable, it is creating a property i for the global object (which may seem/behave mostly like a global variable - but they have some subtle differences).
better would be:
var i;
for(i=0; i<arr.length; i++) {
var j=0;
// ...
}
now the loop is using a global variable i (or function local variable i, if this code appears in a function)
see more about this at what is function of the var keyword and variables vs. properties in Javascript
--
note, what is a little confusing is that you can re-declare a variable, for example in a second loop
for(var i=0; i<9; i++){
document.write('i = ' + i + '<br>');
}
for(var i=0; i<9; i++){
document.write('i = ' + i + '<br>');
}
this seems to be valid (no errors when I test). It seems that you CAN re-declare variables in JavaScript - but it probably isn't every a good idea, unless a special case - see this related question mentioning how [Google Analytics makes use of the 'safe' redeclaration of a variable] (Redeclaring a javascript variable)
there is some discussion about re-declaring variables in JS (and also loop variables like i) in this related SO question: declare variables inside or outside the loop
There is event a JavaScript pattern for single declaration of variables

Categories

Resources