0

the following code goes into infinite loop and a crash in the webpage I need to know what's wrong with it?

    for (var i = 0; i < 2; i+1) {
            for (var j = i; j < 8; j + 2) {
                console.log(arr[j].Qu);
            }
            console.log(arr[i]);
        }
2
  • and what do you try to achieve here, it is unclear, and why j equals i ? Commented Jun 6, 2016 at 10:38
  • 2
    @CeylanMumunKocabaş I wanted to make nested loops based on each others for some business logic in my business Commented Jun 6, 2016 at 10:42

4 Answers 4

4

i+1 doesn't update i's value, therefor, the i always has value 1, as it takes 0+1 in every run, thus never being > 2 and never ending You need to change it with i++, like this

for (var i = 0; i < 2; i++) {

Also, as @Xufox points out, udpate your J loop with

for (var j = i; j < 8; j += 2) {

i+1 is not an assign operation, that's why you need to assign the value urself. i++ and j+=2 translate to

i = i+1;
j= j+2;

and the result of the righthand operation is self-assigned to the variable

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

6 Comments

Same for j which should be j += 2.
@moaatazaamer you've to assign the value back to i using assignment operator i = i + 1 or use the increment operator i++ which is short-cut for same.
@moaatazaamer i + 1 will just return the value of i + 1. In order to save that value back into the variable you would have to do something like this : i = i+1 or the shorthand version i++.
@moaatazaamer if it helped and fixed your erro, please remember to accept the answer.
yes of course I will, but why is that available on languages like C# ( i+1 )
|
1

Value is not assigned back to variable.

 for (var i = 0; i < 2; i+=1) { // i++
            for (var j = i; j < 8; j+=2) {
                console.log(arr[j].Qu);
            }
            console.log(arr[i]);
        }

Comments

1

i+1 doesn't modify i value. You could write instead i++.

Similarly, j + 2 doesn't update j. You should write j += 2.

Here is the corrected code :

for (var i = 0; i < 2; i++) {
    for (var j = i; j < 8; j += 2) {
        console.log(arr[j].Qu);
    }
    console.log(arr[i]);
}

Comments

1

for (var i = 0; i < 2; i+=1) {
        for (var j = i; j < 8; j+= 2) {
            console.log(arr[j]);
        }
        console.log(arr[i]);
    }

1 Comment

Maybe a short sentence which describes the change would be nice. :) (its sometimes hard to spot the difference)

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.