Uncaught TypeError with array

Losing my mind!

On loading a page it uses fetch to get info from a JSON file. And processes this into an array. On clicking a button it then carries out a mathematical function using the info. But in the console I keep getting an error - uncaught TypeError Cannot read properties of undefined.

The first 2 lines of the function are:

console.log(result:"+loaded["y"+ year]["ABC"]);
 var PT = loaded["y"+ year]['ABC'];

The second line is where it has a issue, even though the output of the first works fine. If I add typeof it tells me its an object as well so not exactly sure how anything is undefined. Help!! TIA

In your console.log it looks like you’re missing the first " before “result:”.

The "cannot read properties of undefined means that one of the following doesn’t exist when the function runs:

  • loaded
  • loaded["y" + year]
  • loaded["y" + year]['ABC']

I appear to have butchered the code while I was putting it in here. The " is in the original version and it returns a result, which is why I don’t understand how by the time the next line runs any part of it has vanished, if you see what I mean.

With just those two lines in isolation, if one works than the other should. I don’t know what else might be going on to cause you problems.

I’m glad it isn’t just me! Thanks for taking the time.

Actually turns out I’m wrong. That first line actually now causes the error. The console display comes from a line in the click event, right before it runs the lines I put up.

The code on the main page this all runs on loads “loaded” and will display the value of ABC. So why won’t the function that runs on clicking not pick it up?

Without being able to see the whole thing, it’s really hard to guess. It sounds like the click handler might not have access to the same data that the other function does.

1 Like

In trying to shorten everything to what it needed to be I discovered a change in formula meaning that it was looking for the wrong year basically (instead of 2020 it was 19500 - a totally different input). Thanks for the help. Made me critically breakdown what was going on.

Congratulations on tracking down the issue! These things can be frustrating to debug. Happy coding!

1 Like