3

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

4
  • for (START, LIMIT, INCREMENT) you have for (START, START, INCREMENT) Commented Mar 31, 2016 at 7:16
  • 1
    A single equals sign (=) is assignment operator, you will need to use a double equals sign (==) which is the comparison operator, in the second part of the for loop Commented Mar 31, 2016 at 7:18
  • @Valeklosse Even if put (i == n ) the code is not executing also no error Commented Mar 31, 2016 at 7:51
  • 1
    @Avinash the code probably is executing, but because i (1) is not equal to n (10), it wont enter the loop, in effect the loop will only ever excute once in this manner. If you want it to run until i(1) == n(10), then best to use != or <= Commented Mar 31, 2016 at 11:38

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

for (i=1; i < n; i++){ opposite.
2

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

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.