JavaScript variables declare outside or inside loop?
There is absolutely no difference in meaning or performance, in JavaScript or ActionScript.
var
is a directive for the parser, and not a command executed at run-time. If a particular identifier has been declared var
once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether value
is declared to be var
inside the loop, outside the loop, or both.
Consequently you should write whichever you find most readable. I disagree with Crockford that putting all the vars at the top of a function is always the best thing. For the case where a variable is used temporarily in a section of code, it's better to declare var
in that section, so the section stands alone and can be copy-pasted. Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associated var
, and you've got yourself an accidental global.
In particular:
for (var i; i<100; i++)
do something;
for (var i; i<100; i++)
do something else;
Crockford will recommend you remove the second var
(or remove both var
s and do var i;
above), and jslint will whinge at you for this. But IMO it's more maintainable to keep both var
s, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.
Personally I tend to declare as var
the first assignment of a variable in an independent section of code, whether or not there's another separate usage of the same variable name in some other part of the same function. For me, having to declare var
at all is an undesirable JS wart (it would have been better to have variables default to local); I don't see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.
(*: other than in nested function bodies)
Javascript variable declaration within loop
Because of variable hoisting in Javascript, there is no technical difference in execution between the var
being at the top of the function or inside the for
loop. If that is all you care about, then you can do it either way.
Just to refresh memory, Javascript hoisting means that code like your second code block is parsed and then execute just like your first code block. All var
declarations within a function are automatically moved to the top of the function scope before execution. Assignments to those variables are kept where they are located in the code - just the declaration of the variable is moved.
So, the difference is more about how you want to code to look. When you put the var
definitions inside the for
loop, it makes the code look like the variables are being created anew for each iteration of the for
loop, even though that is not the case. They are being assigned a value each iteration of the loop, but a new variable is not created. That would be the case if you used let
instead of var
since let
has a block scope whereas var
only has function scope.
In general, it is a good practice to only put code inside a loop that actually needs to be inside the loop. While it doesn't actually change anything in the execution whether the var
is inside or outside the loop, it is just part of a good practice whereas other code being inside or outside the loop could make a difference.
In your case, I think this would be a better practice:
function abc(){
var liTags = document.getElementsByTagName('LI');
var divTags = document.getElementsByTagName('DIV');
var len = Math.min(liTags.length, divTags.length);
var a,b;
for(var i = 0; i < len; i++){
a = liTags[i].width;
b = divTags[i].width;
// now do something with a and b
}
return;
}
Here, you've removed the two calls to document.getElementsByTagName()
from the loop which will make a HUGE performance difference.
Update in 2017. Javascript version ES6, now supports both const
and let
for declaring variables. They are block scoped, not function scoped like var
, so if you declare one of them inside a for
loop block, then there will be a new and separate variable created for each invocation of the for
loop. While that wouldn't make any significant execution difference in the type of code you showed, it can make a difference if you had asynchronous code inside the loop that references the variable you were declaring. In the case of const
or let
used within the loop body, each asynchronous call would get its own separate copy of the variable which can sometimes be very handy.
for(var i = 0; i < len; i++){
let a = liTags[i].width;
let b = divTags[i].width;
$.get(someUrl).then(function(data) {
// each call to $.get() here in the loop has it's own a and b
// variables to use here, which would not be the case with var
});
}
Declaring variables inside or outside in a for-in loop
Those two snippets of code do exactly the same thing (and that's the case in most language such as C, C++ and C# amongst others). If the variable was redeclared at every iteration, then following your logic, it would also be re-initialized, and would constantly loop over the same object. Your loop would be infinite.
On a side-note, in JavaScript, all variable declarations get pushed to the function scope; this means that you can declare variables anywhere within a function, even within nested loops, and they will only be declared once.
Link to the var documentation
Relevant SO question
Other relevant SO answer
Edit courtesy of @torazaburo:
If you want to declare a variable with a local scope (as in, a variable that will only be defined in the current block such as a for
, while
or if
, you can use the let
statement:
let var1 = 123;
It also allows you to override variables with the same name but declared in a higher scope, such as in this example from the docs:
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
See the full documentation (and examples) here.
Javascript loop-index declaration outside or inside loop-body?
For var
it does not matter and it will behave the same way either ways. In Javascript the variable declared with var
can be hoisted
.
If you are not using the variable outside the scope defined by the for
loop, the current preference is to use let
instead of var
.
for (let i = 0; i < length; i ++) {
// do something
}
ES6 declaring variables before or in loop
In code snippet A, cols
is accessible outside of the for
too. As let
variables are block-scoped, when used let
to define variable inside for
, the scope of the variable is for that block only. So, in B, the variable cols
will not be accessible outside of the for
.
C, is similar to A if cols
is defined only once. If col
is defined twice in the same scope using let
will result in error.
Which one to use depends on the use-case.
- If
cols
is needed insidefor
only, then uselet cols = ...
- If
cols
is needed outside offor
too, uselet cols;
beforefor
and then it can be used afterfor
too in the same enclosing scope. Note that, in this case,cols
will be the last value assigned in the loop.
Why does declaring the variable outside the for loop print all the elements of an array but declaring first inside the for loop prints only the last?
That's because, when you declare the variable inside the loop, it will be declared each time the loop is repeated. So the last run of the loop will declare an empty variable 'html' and will then push the element into this array. So there is only one element inside your array.
ES6 JavaScript - const inside or let outside loop?
It's going to be difficult to give a definitive answer considering that different browsers have vastly different internal implementations. There could very likely be zero difference. Prior to execution, Javascript in the browser is compiled by the internal JIT compiler, which will very likely recognise a redundant variable declaration inside a loop and optimise it out, like any other good compiler. let
and const
will definitely affect this, I'd say const
would make optimisation out of the loop even more likely considering the compiler can instantly see that it's an immutable atomic variable specific to the inner loop scope.
It would also likely unroll performance intensive loops as well. Javascript has a few other performance quirks though where accessing variables in higher scopes incurs a minor performance penalty, I remember looking into that a long time ago when doing gamdev in the browser. That might not be current anymore, but it was a few years ago.
As others have pointed out, unless profiling has already indicated that this is a serious bottleneck in your application, it is premature optimisation. I'd be extremely shocked if optimising this could possibly contribute any significant performance benefits. If performance in this area matters, best advice is to profile different scenarios yourself and decide what is best for your use case.
Declaring var inside Javascript for loop declaration
These are exactly the same. All local variables in javascript have function scope which means they are alive for the entire function they are declared in. This is often counter intuitive at first as most curly brace languages scope the life time of the variable to the block they are declared in.
A portion of Javascript developers very much prefer the second form. The rationale is that since all variables have function scope, you should declare them at the function level to make the life time explicit even for those not familiar with Javascript. This is just a style though and by no means a hard rule
EDIT
Note that with the introduction of ES6 let, you can now use let inside your loop for real block-scoped variable more details
for(let i = 1; i <= 5; i++) {
setTimeout(function(){
console.log('Value of i : ' + i);
},100);
}
Not being able to reference a variable from outside the loop
That's because a variable defined as const
or let
has "block scope". That means it is only visible inside the nearest set of curly braces. So:
function foo() {
const foo = 'foo-string';
if(1) {
const bar = 'bar-string';
console.log(bar); // This is fine
}
console.log(foo); // This is also fine
console.log(bar); // Error!
}
To solve your problem, you need to define your variable outside of the block defined by the nested for loop. So:
function coinOnTheTable(m, k, board) {
let a;
for(var i = 0; i < board.length; i++){
for(var j = 0; j < m; j++){
if(board[i][j] === "*"){
a = `${i}${j}`;
}
}
}
return a;
}
Note, the reason it changes from const
to let
is because const
variables cannot be reassigned, but since you want to declare it as undefined
(at the start of the function, then assign a string to it (inside the loop), you need to be able to reassign it.
Related Topics
Doesn't JavaScript Support Closures with Local Variables
Canvas.Todataurl() Securityerror
JavaScript Associative Array to JSON
Template String as Object Property Name
Setting Query String Using Fetch Get Request
How to Convert Blob to File in JavaScript
Using Http Rest APIs with Angular 2
When Does Js Interpret {} as an Empty Block Instead of an Empty Object
How to Map More Than One Property from an Array of Objects
How to Return Values from Async Functions Using Async-Await from Function
How to Guarantee That My Enums Definition Doesn't Change in JavaScript
What Is "Export Default" in JavaScript