Jonathan Bechtel
Jonathan Bechtel

Reputation: 3607

Uncaught TypeError: Cannot read property of undefined - javascript

I know this question has been asked before, but I've looked through the different versions of this question and am not seeing an answer for my particular issue.

My code:

var display = {

difference: function(a) {
    return Math.abs(state.price - state.greens[a].pricePer30);
},
// Some more methods here

When I run the code, I get this:

Uncaught TypeError: Cannot read property 'pricePer30' of undefined

However, if I run

console.log(display.difference(0))

It returns the correct answer.

When I read this question:

I thought that perhaps the argument I was using was in fact being re-used somewhere else in the script, so I changed the argument to read:

var display = {

difference: function(num) {
    return Math.abs(state.price - state.greens[num].pricePer30);
},
// Some more methods

But I get the same error message.

What should I look for in my code to fix this?

Upvotes: 0

Views: 2137

Answers (1)

Georgios Dimitriadis
Georgios Dimitriadis

Reputation: 685

The problem is clearly that state.greens[a] is undefined for a specific index a. Add a check before to get rid of the immidiate problem, but I'm guessing you're gonna have to investigate why it's undefined for index a as well.

if(typeof state.greens[a] !== "undefined") {
    return Math.abs(state.price - state.greens[a].pricePer30);
} else {
    console.warn("Found undefined state for index: ", a);
}

Upvotes: 1

Related Questions