JavaScript: setInterval and for loop explanation - javascript

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.

Related

'For loop' within a function

I hope everyone is having an amazing day so far.
I am asking for help on an exercise that I am stuck on. I have gone through and researched all over but still am not getting it right.
The task is:
Create a for loop in which an iterator starting from 0 up to the iteratorMax value (not included) (the second parameter to your function) is incremented by 1. Add the iterator to num(the first parameter to your function) for each incrementation. you must return the number at the end of your function.
I was given this code to start with:
function IncrementNumber(num, iteratorMax){
//Add For loop here
//return value here
}
I have tried coding it a number of different ways but still not correct.
for example:
function IncrementNumber(num, iteratorMax){
for (let i = 0; i < iteratorMax; i++) {
return(i);
}
}
I have tried to declare "i" but that seems to be incorrect also.
I really appreciate any help or hints to what I am missing or doing wrong in my code.
Thank you!
For the IncrementNumber(value, N) method, when value is 0, this algorithm returns the result of the equation:
Total = N x (N-1) / 2
function IncrementNumber(num, iteratorMax){
for(let i = 0 ; i < iteratorMax ; ++i){
num += i;
console.log(`i: ${i}\tnumber: ${num}`);
}
return num;
}
console.log(`Result: ${IncrementNumber(0, 10)}`);
If you call return within the loop, the loop will only be executed once.
You need to move the return statement outside of the loop.
Whenever calling return, this will cause the current function to exit.
function IncrementNumber(num, iteratorMax){
for (let i = 0; i < iteratorMax; i++) {
num += i;
}
return num;
}

visual studio code doesn't run for-loop when condition is set to i = parameter

i wanted see what the output will be if the condition for executing the code block is i = num. when i run the code, vs code terminal just shows node (path of my file) and i subsequently cannot execute any code from any file again. i must restart vs code and change the condition to i < num. why is this so? running the code in the code snippet here also seemingly crashes the page.
is this an infinite loop? however i don't see how it is an infinite loop as the condition to run the code is i=num. if i =/= num, shouldn't an error be returned instead of crashing vs code?
function FirstFactorial(num) {
let solution = 1
for (let i = 1; i = num; i++){
solution *= i
}
return solution;
}
console.log(FirstFactorial(5))
One thing to address. The second parameter for the for loop should be a condition.
i = num
is not a condition.
If you want to compare those variables you can use the triple ===
the issue is the i = num in your:
for (let i = 1; i = num; i++){
you want i <= num for the for loop to iterate.
for (let i = 1; i <= num; i++){
solution *= i
}
The for loop iterates while the second block i <= num evaluates to
true.
As soon as its false it will break out of the for loop,
as 1 != 5 (where num is 5 in your example) having i = num; as your second block evaluates to false right away and the for statement does not run.

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);
}

Strange behaviour of for loops

Can anyone tell me why for loop increments even on failed iteration?
for (var n = 0; n <3; n++) {
alert(n); // displays 0 , 1 , 2
}
alert(n); // gives 3
But shouldn't it be like
if(condition):
//desired stuff
increment;
else:
exit;
I seldom use iteration variable mostly I just throw them away upon loop completion but in this case found it to be the cause of a bug
Conceptually n++ is called just after the final statement of the loop body, and the stopping condition is evaluated just before the first statement of the loop body.
So your code is equivalent to
for (var n = 0; n < 3; ) {
alert(n);
n++;
}
Viewed this way, the reason why n is 3 once the loop exists ought to be obvious.
Note that in javascript, n leaks out of the for loop.
for (var n = 0; n <3; n++) {
alert(n);
}
alert(n);
Working of for loop is as follows -
First it initialize the n to 0;
Then it checks the condition whether it is true or not in this case condition is n<3.
Finally it increments the n and again check the condition and if it is true,It again goes in for block. And if the condition is false, It exit the for loop.
In your code when n=3 condition get false. So final value of n is 3.
Just executed the code at chrome console:
It works as expected.
As you have commented that n will be alert with 3, it is wrong, because when n will be 2, condition will be checked i.e. 2<2 will be wrong, then it will be jump from the loop and will alert 2 not 3.

how restricted is recursion in javascript?

I guess its to stop browsers getting nailed all the time by duff code but this:
function print(item) {
document.getElementById('output').innerHTML =
document.getElementById('output').innerHTML
+ item + '<br />';
}
function recur(myInt) {
print(myInt);
if (int < 10) {
for (i = 0; i <= 1; i++) {
recur(myInt+1);
}
}
}
produces:
0
1
2
3
4
5
6
7
8
9
10
10
and not the big old mess I get when I do:
function recur(myInt) {
print(myInt);
if (int < 10) {
for (i = 0; i <= 1; i++) {
var x = myInt + 1;
setTimeout("recur("+x+")");
}
}
}
Am I missing something or is this how you do recursion in JS? I am interested in navigating trees using recursion where you need to call the method for each of the children.
You are using a global variable as loop counter, that's why it only loops completely for the innermost call. When you return from that call, the counter is already beyond the loop end for all the other loops.
If you make a local variable:
function recur(int) {
print(int);
if (int < 10) {
for (var i = 0; i <= 1; i++) {
recur(int + 1);
}
}
}
The output is the same number of items as when using a timeout. When you use the timeout, the global variable doesn't cause the same problem, because the recursive calls are queued up and executed later, when you have exited out of the loop.
I know what your doing wrong. Recursion in functions maintains a certain scope, so your iterator (i) is actually increasing in each scope every time the loop runs once.
function recur(int) {
print(int);
if (int < 10) {
for (var i = 0; i <= 1; i++) {
recur(int+1);
}
}
}
Note it is now 'var i = 0' this will stop your iterators from over-writing eachother. When you were setting a timeout, it was allowing the first loop to finish running before it ran the rest, it would also be running off the window object, which may remove the closure of the last iterator.
Recursion is very little restricted in JavaScript. Unless your trees are very deep, it should be fine. Most trees, even with millions of elements, are fairly wide, so you get at most log(n) recursive calls on the stack, which isn't noramally a problem. setTimeout is certainly not needed. As in your first example, you're right that sometimes you need a guard clause to guarantee that the recursion bottoms out.

Categories

Resources