How To Identify Coin Value (JavaScript)?


How can I identify coin value in JavaScript?

In the level I am currently working on (Shine Getter in the Desert world), the goal is to only collect gold coins so that you can get more gold more quickly. The goal of this level is to aid in my understanding of arrays, so I need to use them. Here's what I have:

Basically, how it should function is that repeatedly, the hero finds an array of items (given the only item type is a coin), and cycles through each one: if it has a coin value of 3, then the hero should move to the coin. However, the program is telling me that I “cannot read property ‘value’ of undefined”. What does this mean? How can I fix it? Another thing – The “if coin value == 3” script was put in automatically. So why is it reading it like it’s an error? If anyone could help, I’d be grateful.


coinIndex <= coins.length

Let’s suppose there are no coins, then coins.length == 0 and your while-loop goes inside, but there are no coins :slight_smile: As the result your coin is undefined.



.1. When dealing with arrays in Javascript the counting starts at 0. If we talk about an array with 3 elements in it the following will be true.

0 = 1st place
1 = second place
2 = third place
3 = fourth place (or undefined)

Now here is where a challenge exists. What does the value of coins.length give you? Use: hero.say(coins.length); to find out.

If you then look at your while loop logic statement again the answer should slowly become clear:

while (coinIndex <= coins.length) {

.2. And as @Bryukh mentioned there is the case where there may not be any coins.


Indeed – But coins are constantly being generated in the level; I should have clarified, sorry.


Thanks for the help!

I now see the error of my ways; since the array items start at 0, and the hero, when counting coins, starts at 1, I need to subtract 1 from the coins.length, because the hero always attempted to locate the value of a coin that never existed! Thanks so much!

while (coinIndex <= coins.length - 1) {


I know. I tried to explain for the simplest case. The case when there are coins is explained by Harry.


while (coinIndex < coins.length) {


Don’t worry – I got it already :3 Refresh the page :slight_smile: I had already sent a thank-you message :slight_smile: