Diego Alves
Diego Alves

Reputation: 2669

Strange behavior in for loop, statements not executing

I will show my code and some images to demonstrate the problem.

A simple statement like a variable declaration or using the log function causes the json result to be undefined. When I type in the text input, the ajax call is executed and returns the data.

updated Here is my code included as text. When copy and paste the code the problem of the missing curly braces is very clear. As you can see in the pictures VS 2017 doesn't help you notice missing braces easily, they could improve it.

for (var i = 0; i < data.length; i++)

                   console.log("some message");
               console.log(data[i].titulo);

enter image description here

removing the statement:

enter image description here

Now check this out, When there's a statement in the for loop it seems that it is evaluated only once.

enter image description here

When I took the statement the 'i is x' is executed more times.

enter image description here

Upvotes: 0

Views: 28

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 121998

Nothing to do with the json you using. Purely about the for loop without using curly braces.

You missing the {} for your loop. Without {} only the first statement is belong to the for loop

So in your case 1, your code is equal to

for ( ..) {
 console.log(..);
}
console.log(data[i]...)

And it is working in case 2 because you remove the console log statement and hence it is equal to

 for ( ..) {
     console.log(data[i]...)
 }

If you want to have both statements inside for loop use {}

for ( ..) {
         console.log(..);
         console.log(data[i]...)
     }

Not only to have multiple statements, even for a single statement, try to use {} always just to avoid confusions like this.

Upvotes: 2

Related Questions