What is the difference between:
for (var i=0; i<5; i++) {}
for (i=0; i<5; i++) {}
And is it necessary to include the var keyword?
I understand that the var keyword affects variable scope, but I'm having trouble understanding if it's necessary to include the keyword in for loops.
In the second example, your variable is defined globally, so if you're in the browser environment, you can access it from the window object.
The first one is an equivalent of:
var i;
for (i=0; i<5; i++) {}
as all the variables in javascript are hoisted to the beginning of the scope.
1
for (var i = 0; i < 5; ++i) {
// do stuff
}
2
var i;
for (i = 0; i < 5; ++i) {
// do stuff
}
3
for (i = 0; i < 5; ++i) {
// do stuff
}
1 and 2 are the same.
3 you probably never mean to do — it puts i in the global scope.
I am assuming your are using C#, Java or JavaScript. The short answer is you need the var if "i" has not already been declared. You do not need if it has already been declared.
For example:
var i;
for(i=1;i<=5;i++) {}
Now there may be some implicit variable typing depending on language and IDE, but relying on implicit typing can be difficult to maintain.
Hope this helps, good luck!
Related
Can someone explain that why the value of i with the var keyword changes after re-declaring the same variable in a for loop?
For example the value 10 is set to variable i and after setting the condition in for loop i < 40 the value changes to i?
var i = 10;
for (var i = 0; i < 40; i++) {
// code block
}
document.getElementById("demo").innerHTML = i;
<div id="demo"></div>
var statements are scoped to the function they are declared within and the for loop is in the same function as the line immediately before it. (For historical reasons, redeclaring a variable with var doesn't throw an error, it is just silently ignored (although the assignment isn't).)
Use a let statement if you want a variable scoped to the block.
Because in the first part of your loop, you are re-declaring the same var.
To solve this, you must change the name of the first "i" var. For example "j"
And on the first part of your loop, equal "i" to "j" -> var i = j
Here is the snippet
var j = 10;
for (var i = j; i < 40; i++) {
// code block
}
document.getElementById("demo").innerHTML = i;
<div id="demo"></div>
I am new to programming and sorry if a question is dumb.
I am using several functions with variables i, j for looping like - for( j = 0; j < pol.length; j++) ...
Now my lack of knowledge is - I think that declaring "var i = 0..." in every function will creates a memory problem because these functions are used many times and it will declare "i" or "j" each time. So what I do now is I declare var i,j = 0; once outside the functions as a global and then just use them in functions without "var". But I have a feeling - this is terribly wrong.
Another variables that I declare as global "var" are the ones I use later in some functions. For example - var pol_owner = ""; So the code will play with these variables later and change their values. And now I have something like this at the start of my document:
var thePol = 0;
var nondrag = 0;
var intGl = 0;
var intMn = 0;
var oldGl = 0;
var oldMn = 0;
var money = 0;
var gifts = 0;
var g_spent = 0;
var the_mess = "";
var j = 0;
var x = 0;
var y = 0;
var i = 0;
And later my functions just use these variables without "var".
I know though the code runs well still I am doing it wrong. Can you give me any advice of how to properly do it. I was looking for some information about it but still I am not sure what is the proper way of doing it.
From the start I was doing my code as: for( var j = 0; j < pol.length; j++) not declaring "j" outside the function, but later I thought that every-time this function run it will declare this var again and again and will not it be more effective to declare it once from the start and later use it without "var". The only problem I see is - creating a global variable that I can accidentally use wrong in some part of the code. But I am kind of controlling this.
So the question basically is - is declaring "var i=0" in every loop part of the function creates any memory problem and should I declare this var once outside the function and use it later without declaration to avoid this problem?
Thank you in advance.
I am learning javascript and came across a topic which mentions that the variables declared inside a function is available anywhere inside the function and javascript puts the variable definition at the top like in the below example:
var functionScope=function(){
for (var i=0; i< 10; i++){//code inside this loop}
return i;
}
console.log(functionScope()); //prints 10
The javascript actually turns the above function to the below:
var functionScope=function(){
var i;
for ( i=0; i< 10; i++){//code inside the for loop}
return i;
}
console.log(functionScope()); //prints 10
Since javascript is interpreted language, it executes line by line. How will it know that it should pull the variable to the top of the function after it has tried accessing the variable. When it tries to access the variable it should tell as undefined right?
Also if I go by the theory that the variables will be placed at the top of the function and can be accessed anywhere then the below code should print 10, but why the below code prints undefined?
var functionScope=function(){
console.log('The value os i is '+i);
var i = 20;
}
console.log(functionScope());
Could someone explain where my understanding is wrong?
One more doubt: Typically in Java, if I had to print the value of i outside the for loop, i would get an error, but in javascript does the variable still accessible outside outside the for loop as in case of fist example where the variable is defined inline inside the for loop. Am i missing something here?
var functionScope=function(){
for (var i=0; i< 10; i++);
return i
}
console.log(functionScope()); //prints 10
This is only a bad indentation. Because of the ; at the end of for, it doesn't includes the return i statement into the loop.
There is the well indented one to help you understand what really happens:
var functionScope=function() {
for (var i=0; i< 10; i++)
/* do nothing */;
return i
}
With var, you tell the JS that the variable is not global, and it'll be aviable only inside the function.
With =, you can set the variable's value.
var i; for (i = 0; ... and for (var i = 0; ... is the same.
In the third example, you don't have i inside the function. In this case, the JS'll try to find it as a global variable, outside the function. If you've set window.i = 1, it'll print The value os i is 1, otherwise it'll generate an error, because i is not defined nowhere.
var i = 0;
var fn = function() {
i = 1; //window.i = 1;
};
console.log(i); //prints 1
var i = 0;
var fn = function() {
var i = 1; //fn.i = 1;
}
console.log(i); //prints 0
var fn = function() {
var i = 1; //fn.i = 1;
}
console.log(i); //ReferenceError: i is not defined
var i;
var fn = function() {
var i = 1; //fn.i = 1;
}
console.log(i) //prints undefined
As Sebastien C. has already told you, your example code dosn't do what you want it to do. for (var i=0; i< 10; i++); means for (var i=0; i< 10; i++) {/*do nothing*/}. If you remove the ;, you'll notece your function will return 0, because the return keyword stops the function, and it return the value, no other operations will be executed, your loop will run only once.
Also, you should use ++i.
Yes Javascript is interpreted and whenever is finds a var declared/undeclared, it declares it and then performs the operations or in technical terms it does var hoisting. So now the variable is declared, but is undefined.
So any operation done on it (other than assignment) will result in its value being undefined only. eg;
{
x++ ;
var x = 10 ;
console.log(x);
}
will print 10. So you can think of it as
{
var x = undefined; \\variable hoisted at beginning of block
x++ ;
x = 10 ;
console.log( x ); \\ x = 10
}
I am having a jstree and in javascript function i am checking which node has been selected thats working fine. But when i assign that node value to a variable then do comparasion with a normal string variable thats not working.
$(document).ready(function() {
$('#bdeViewNew').on('changed.jstree', function(e, data) {
var i, j, r = [];
for (i = 0, j = data.selected.length; i < j; i++) {
var x = data.instance.get_node(data.selected[i]).text;
r.push(data.instance.get_node(data.selected[i]).text);
if(x=="Hadoop")
{alert("hi");}
else{
alert("hello");
}
}
});
});
any one know how we can do such comparasion?
thanks in advance
It is possible that your variable has some unexpected whitespace at the start or the end, that's a common problem. You should be able to get rid of it with
var x = data.instance.get_node(data.selected[i]).text.trim();
Should work on all modern browsers.
Also keep in mind that JavaScript has function scope, not block scope like you might be used to from C/C++ or Java. The x you declare there is visible throughout the function, not just in the for loop. You should probably declare it at the same time as i, j and r.
Statement 1
var i = 0;
for (; i < 10 ; i++);
Statement 2
for (var i = 0 ; i < 10 ; i++);
Are those two statements equal?
Nope, no difference between the 2 examples, functionally.
However, statement 2 can cause confusion. This is because i is not scoped to the for block, it's accessible outside of that for loop, which can result in a polluted global scope.
Just make sure you keep track of your variables when using them like statement 1.
Personally, I prefer something like this:
var i;
for(i = 0; i < 10; i++){
// Do stuff
}
for(i = 0; i < 20; i++){
// Do other stuff
}
This way, you'll always have your iterator properly set.
There are no specific differences. Javascript's variable's scope is different from other languages like C#. This is already discussed here