mb432
mb432

Reputation: 11

Uncaught TypeError: Cannot read property foo of undefined

My JavaScript:

todo.completed = !todo.completed;

ERROR:

Uncaught TypeError: Cannot read property 'completed' of undefined
    at Object.toggleCompleted (script.js:34)
    at Object.toggleCompleted (script.js:89)
    at HTMLButtonElement.onclick ((index):33)
toggleCompleted @ script.js:34
toggleCompleted @ script.js:89
onclick @ (index):33

Am I missing something here?

Upvotes: 0

Views: 971

Answers (3)

Jeffrey R Johnson
Jeffrey R Johnson

Reputation: 1

What's so confusing about it is that the code will work in Plunkr, glitch or codepen, but not a text editor and browser, because of the way those sites's routing is set up. In your index.html file you need to replace <script src = "filename.js></script> with <script src="entire path to filename.js"></script>

Upvotes: 0

Keith
Keith

Reputation: 155662

The variable todo has passed out of scope. It's probably declared in a function that is outside the closure of handlers.toggleCompleted() when it is called.

There are a couple of ways to fix this, but as the simplest you can just make todo global:

  1. Find var todo and remove var from the start.
  2. At the top of your JS add var todo = {};

This will make todo a global object that's always defined on your page.

Upvotes: 0

Sam D.
Sam D.

Reputation: 57

It looks like you haven't declared the variable todo yet. Try something like todo = {}; Let me know if you have questions!

Upvotes: 1

Related Questions