Shine Getter Javascript

When do I put this.findItems() in the loop and when don’t I do this?
This depends whether you want to run the command multiple times or not. If you want the command to run multiple times, you put it in a loop. If you want to run it only once, you don’t put it in a loop. Simple as that.


Attention, Techie-Talk incoming!
I will talk about loops and what the computer does to them. This is not required to understand the answer. It may help you understanding what happens inside your computer though.

The code you write will be executed once for the whole level.

It will start at the top and run till the last instruction. If the computer finds a loop- or a while- command, it may jump to an earlier point of your code, exactly to the loop-command.

A loop can cause your program to run forever. Actually, this is what loop does. while is a bit nicer. If programmed right, it can stop running. loop {...} is the same as while(true) {...}

Back to topic:
Let’s say a levels ask us to collect all items. The items are already present, they do not spawn later. Your code would look like this:

var items = this.findItems();    //1
var index = 0;                   //2
                                 //3
while(index < coins.length){     //4
    //collect item               //5
    index = index +1;            //6
}                                //7
                                 //8

Lines 1 and 2 are outside of the loop. They will be executed exactly once. The program then executes line 4 once. If (and only if) the condition is true, the program goes to line 5. Let’s say we found an item. The program executes line 5 and 6. The program then goes to line 7. Line 7 is the end of the loop. Instead of executing line 8 next, the program goes to line 4. Let’s say this time that the condition becomes false. Now, the program goes to line 8. As line 8 is the last line, the program ends.

We now look at the execution order a bit summarized (Note: items.length = 1, that is we have 1 item):

/*
For clarity, I directly resolved variables. This is important for the if-statements
*/

Execute Line 1    -> var coins = this.findItems()
Execute Line 2    -> var index = 0
Execute Line 3    -> 
Execute Line 4    -> if 0 < 1 then GOTO LINE 5 else GOTO LINE 8
/*    -> GOTO Line 5                             */
Execute Line 5    -> //collect coin
Execute Line 6    -> index = 0 + 1
/*    -> index is now 1                          */
Execute Line 7    -> GOTO LINE 4
/*    -> Translated: GOTO start of while-loop    */
Execute Line 4    -> if 1 < 1 then GOTO LINE 5 else GOTO LINE 8
/*    -> GOTO Line 8                             */
Execute Line 8    -> 
>>> End of Program

As you can see, there is a lot of GOTO going on here. Sadly, reading a program made understandable for a computer makes it almost unreadable for a human.

1 Like