for loop declaration, are those two statements equal? - javascript

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

Related

What happens if you put an iteration count of a for loop as a variable?

I want to make a program in javascript in which a person inputted the iteration count for a for loop(they could input x++, or y--), but I don't know if I am using the right method.
Here is my code:
var x = prompt("iteration count")
// x should equal something like, i++, or x--
for(var i = 0; i < 10; x){
document.write(i)
}
But when the code ran the program kept crashing.
Why is it crashing and how do I fix this?
Please Help
you need to parse the int value of x because it's a string and use it to increment i
var x = parseInt(prompt("iteration count"))
for (var i = 0; i < 10; i += x) {
document.write(i)
}
EDIT :
based on the question edit and the comments, you can use eval(), but :
Do not ever use eval!
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
So before you use it, read the MDN page and check : eval isnt evil it's just misunderstood
where there's this comment from Spudley :
From a security perspective, eval() is far more dangerous in a server
environment, where code is expected to be fully trusted and hidden
from the end user.
In a browser, the user could eval any code they wanted at any time
simply by opening dev tools, so as a developer you can't get away with
having anything on your client code that could be insecure against
eval anyway.
to test the snippet below, type i++ in the prompt
var x = prompt("iteration count");
for (var i = 0; i < 10; eval(x)) {
console.log(i)
}
an alternative to eval() would be new Function or check the answers here : Programatically setting third statement of for loop
var input = 'i++';//Or whatever condition user passing in
var conditionProgramatically = () => new Function(input)() ;
for (var i = 0; i < 10; conditionProgramatically()) {
console.log(i)
}
For for-loop, third statement will be invoked/executed on every iteration, and hence we set a function call, and in that function, we execute whatever user passing in as you've mentioned i++
That is an endless loop because the variable i never incremented. Try this one.
var x = prompt("iteration count")
for(var i = 0; i < x, i++){
document.write(i)
}
You forgot to increment the index variable, it result to endless loop and maximum stack error, you can also use + for parseInt shorcut.
var x = +prompt("iteration count")
for(var i = 0; i < x;i++){
document.write(i)
}
You have to parse the input value and then make it as a condition to stop iterating after the given value.
var x = parseInt(prompt("iteration count"))
for (var i = 0; i < x; i++) {
document.write(i);
}

JavaScript variables declaration that are used in functions

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.

JavaScript: setInterval and for loop explanation

i searched around for a couple of questions related to the use of the for loop and the setInterval function in JavaScript but i couldn´t find a concrete answer on why this snippet doesn´t work. Could someone explain please what´s happening under the hood and why this code doesn´t print anything at all?
for (let i = 0; i++; i < 10) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Your for loop is not correct. The condition needs to be the second statement in the for loop.
Following code should work.
for (let i = 0; i < 10 ; i++; ) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Expected Syntax for loop. You can read more here
for ([initialization]; [condition]; [final-expression])
statement
EDIT 1:
Though all answers (including mine) mentioned that condition needs to be second statement in the for loop which is correct. There is one more additional important behavior.
The for loop for (let i = 0; i++; i < 10) is actually correct in terms of grammar and even the javascript runtime executes this code.
But, as in your case, if the condition is evaluating to falsy value then it would exit the loop.
Breaking your for loop for (let i = 0; i++; i < 10) into each seperate construct
Initialization: let i = 0; This statement initializes the value of variable i to 0.
Condition: i++; Javascript evaluates the statement to check if the statement is true or not. In case of i++ the runtime firstly checks for the current value of i which is 0 . Since 0 is considered a falsy value the condition evaluates to false and hence the statement is not executed. Also, i++ statement is a post increment which basically increments i and then result the original value of i.
So, if you would have written loop like below, using the intiliaztion of i=1, then it would have worked, though it would be running infinitely untill the browser/Server crashes as the condition i++ would always evaluate to true. I hope that makes sense.
for (let i = 1; i++; i < 10) {
// Statements would run
}
Or
for (let i = 0; ++i; i < 10) { **// Pre increment**
// Statements would run
}
Or
for (let i = 0; i=i+1; i < 10) { **// increment i by assigment
// Statements would run
}
Douglas Crockford in his book Good Parts mention about the usage of ++ & -- and how it can confuse readers.
your for loop syntax is wrong, should be
for (let i = 0; i < 10; i++)
your setInterval code will run every 100 milliseconds for each iteration of the loop (so 10 times every 100 milliseconds)
Nothing to do with setInterval, you simply malformed your for loop:
This:
for (let i = 0; i++; i < 10)
Should be this:
for (let i = 0; i < 10; i++)
First declare the initial state of the loop, then the terminating state of the loop, then the incremental change of the loop.
Observe.

explanation on javascript variables inside a function

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
}

Variable declaration necessary in for loop?

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!

Categories

Resources