I wrote a this simple code in js.
var n=10;
for (i=1;i=n;i++){
console.log('avinsyh');
}
But the loop executes greater than 2000 and crashing the browser.Why this is happening so?
Note: If I Execute this:
var n=10;
for (i=1;i<n;i++){
console.log('avinsyh');
}
Then the javascritpt outputs the correct results
3 Answers 3
It's the assignment in the comparison part of the for loop, which makes an infinite loop. i becomes always n and evaluates to true.
for (i = 1; i = n; i++){
// ^^^^^
var n = 10,
i;
for (i = 1; i <= n; i++){
document.write('i: ' + i + '<br>');
}
1 Comment
for (i=1; i < n; i++){ opposite.in your first for loop , i=n will set i equal to the value of n and thus return a truthy value(as n is not 0) and you get a infinite loop.
Comments
In your for loop you are assinging the value i = n which is always true and hence results in infinite loop.
The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. If the condition expression is omitted entirely, the condition is assumed to be true.
In your second case you are comparing the value of i on each iteration and hence you are getting the expected result.
The basic syntax of for loop is:
for ([initialExpression]; [condition]; [incrementExpression])
statement
So in your first case you are not providing the [condition] rather it is an assignment.
for (START, LIMIT, INCREMENT)you havefor (START, START, INCREMENT)