Daiaiai
Daiaiai

Reputation: 1089

property undefined - how to solve

I get an error message

Uncaught TypeError: Cannot read property 'top' of undefined
at VM32939 own.js:819

for

var hands_corrected = (hands_original.top + 680)

and that's correct, as "hands_original" isn't used on any page of my project, so hands_original is then undefined and thereby wrong.

I try to solve it therefore with

var hands_corrected = (hands_original.top + 680) || 0;

but that still gets me that error. What do I do wrong?

Upvotes: 0

Views: 60

Answers (3)

Sinisa Bobic
Sinisa Bobic

Reputation: 1311

There is two things with what you need to be careful hands_original and hands_original.top so I perfer to check them both on this way

var hands_corrected = (typeof(hands_original) != 'undefined' && typeof(hands_original.top) != 'undefined') ? hands_original.top + 680 : 0;

if check only hands_original.top, and hands_original is undefined we will got "ReferenceError: hands_original is not defined" so I suggest to check both like in my code

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68635

You can use

var hands_corrected = (hands_original && hands_original.top + 680) || 0; 

Or

var hands_corrected = hands_original ? hands_original.top + 680 : 0;

Upvotes: 1

brk
brk

Reputation: 50291

It seems hands_original is an object and it has a key by name top.In this case the object hands_original seems to be undefined , so it cannot find the key top

var hands_corrected=hands_original && hands_original.top+680||0;

By this code you are checking if hands_original is defined, if it is defined then add a num to it the value of it's key top. If hands_original is undefined then assign 0 to hands_corrected variable

Upvotes: 0

Related Questions