Strange behaviour of for loops - javascript

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.

Related

Don't understand why my for loop code isn't working

I was playing with the break and continue keyword but I notice in chrome console this code doesn't work
for (let i = 0; i > 5; i++) {
console.log(i);
} //this will print all number from 1 to 5 but console showing undefined
However I tried changing i = 5 or i === 5 still it doesn't work
But when I changed it to i < 5 then it yields correct result.
Why is that?
your condition is i > 5. At the beginning i = 0 so it will not run ever.
put i < 5
Please check following diagram
Condition getting false on the first time so code block won't execute
i<5 indicates that the for loop will run as long as i is less than 5. i>5 indicates that 0 is less than 5 (let i = 0). So the correct program should be -
for (let i = 0; i <= 5; i++) {
console.log(i);
}

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.

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.

loop flowing steps

This function come from the book "Eloquent Javascript", chapter 3, function.
I don't understand the flowing of the script.
Here is a "for loop" with an impossible mission to make a count value that is equal to 0 and smaller than 0.
At the beginning I expected that it would stop the program but the program is smart. why the impossibility to run the loop doesn't stop the program?
Here is the snippet:
var power = function (base, exponent) {
var result = 1;
for(var count = 0; count < exponent; count ++) {
//repeat as many as needed the self multiplication.
console.log("count = ", count);
result *= base;
console.log(result);
}
return result;
};
console.log("finally we get the number ", power(2, 0));
/* A little question with exponent = 0
Why is that not an error. It is impossible to initiate
with count = 0 && count < exponent.
Weird.*/
The output in repl.it
Native Browser JavaScript
finally we get the number 1
Because count < exponent or rather 0 < 0 is false, so the loop doesn't run and it returns the value of result when it was defined as 1:
var result = 1;
for(var count = 0; false; count ++) {
// This doesn't run
}
return result; // So it's still 1
Thanks to fuyushimoya, I understand:
The first statement in the parenthesis is the initialization of the variable. It is atated anyways before the loop begin. The second statements is a condition, evaluated before the loop is executed, if this statement boolean value is true, the statement inside the loop is executed. after each loop iteration. It change the variable value and then this new value is tested by the second statement and eventually the loop iterates again.
In a case in which the second statement is false at the beginning, the loop doesn't run and the situation is as if we have the first statement alone. See the documentation.

Pre-decrement operator in JavaScript while loop causes stack overflow

Recently I was going through some JavaScript code and at multiple places they are using a while loop to iterate over arrays. The way they do it is as
var i = dataArray.length;
while ( i-- ) {
// iterating over the array.
}
We know that the post-decrement operator here would first supply the value to while call and then will reduce it by one. So in this case for the first iteration if the array length is 10, the while call checks for i to be 10 and we get the value of i inside the loop to be 9. This continues till i reaches a value of 0 and then we exit out of loop. Precisely speaking we are iterating the array in a reverse manner.
This is fine. Where it really confuses me is when I write a pre-decrement operator, the while loop runs forever resulting in a stack overflow.
var i = dataArray.length;
while ( --i ){
// This loop would run forever.
}
Why is this happening? Won't doing --i will also result into i hitting the 0 value at some point of time and breaking the loop?
This is only the case if dataArray is empty. In that casen i = dataArray.length becomes zero. Then when you enter the while loop, i is pre-decremented to -1. Since all non-zero numbers evaluate to true, the loop keeps on going forever.
However, if the array has any elements, this will not happend and the loop will terminate. This code will illustrate the effect without craching anything:
function loop(x) {
var i = x.length;
while ( --i ) {
console.log(i);
if(i == -5) break; //Break after a while so we avoid an endless loop.
}
}
loop([]);
loop([1,1,1]);
The output of the first call is -1, -2, -3, -4, -5, and the output of the second call is 2, 1.
JSFiddle.
Ideal way of writing While loop.
while(condition){
// Your code
// iterator update (i++/i--)
}
Why you loop stops? JavaScript considers 0 as false and stops when reaches 0.
Also can't tell why predecrement runs forever. This might be because i never reaches 0;
Loop simulation
var data = [];
function createArray(){
for (var i=0; i<10; i++){
data.push(i);
}
}
function preDecrementLoop(){
var i = data.length;
while(--i){
console.log(i);
}
}
function postDecrementLoop(){
var i = data.length;
while(i--){
console.log(i);
}
}
(function(){
createArray();
console.log("pre decrement");
preDecrementLoop();
console.log("post decrement");
postDecrementLoop();
})()
Note: --i will skip loop for 0 since 0 is considered as false, while (0) == while (false).

Categories

Resources