Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to make sure a for loop does not restart when a return statement is made?

Whenever I return a GPA value from an 'if statement' nested inside a 'for loop' my 'for loop' resets. As you can see in the console, the counter variable 'c' in my 'for loop' is always equal to 0. How do I stop this behavior?

Snapshot of code: https://w.trhou.se/zswi6lde0l

Lines: 85-114 are the only important ones.

1 Answer

Steven Parker
Steven Parker
229,783 Points

The variable "c" is always 0 because the function always returns during the first pass and the loop never gets a chance to repeat (and to increment "c").

The loop starts again fresh when the function is called again by the "map". This will happen for each element of "subarray" and the entire thing is repeated for each "subarray" in "convertToLetter".

Yes, but how do I prevent this behavior (have the loop repeat) even after returning a value/string to the function.

Edited: Good news! I found a way to work around this by using the parameter index(which will still increase by 1 even after the function returns a value/string). I'm using this instead however, I have come across a new problem. For some reason

console.log(APindex[index]);

returns undefined, why does this occur?

Here is a snapshot of the changed code: https://w.trhou.se/cou06fq2dp

Steven Parker
Steven Parker
229,783 Points

It looks like an item is only pushed onto the APIndex array when the GPA is "AP", but an attempt to reference an item at "index" happens for every second subarray item (i == 1).

Thanks for all the help so far Steven, I'm still not understanding why it does not work, I made a new question for you to answer that: https://teamtreehouse.com/community/why-does-this-not-work-28

Thanks for all the help so far, Sid