Alex
Alex

Reputation: 68492

Checking if variable exists in javascript doesn;t work

Tried:

var xxx = (typeof my_var.property !== 'undefined') ? my_var.property : 'fu';

I get:

Uncaught exception: ReferenceError: Undefined variable: my_var

well I know it's undefined, but why do I get that error?? xxx should take the fu value...

Upvotes: 1

Views: 275

Answers (5)

Murtaza
Murtaza

Reputation: 3065

i think you should first check for my_var

if(!myvar) 
{
     var xxx = (typeof my_var.property !== 'undefined') ? my_var.property : 'fu';
     alert(xxx);
}

Upvotes: 1

Prashant Bhate
Prashant Bhate

Reputation: 11087

Add another check for my_var

var xxx =  (typeof my_var != 'undefined' && typeof my_var.property !== 'undefined')? my_var.property : 'fu';

Upvotes: 2

Martin.
Martin.

Reputation: 10529

Try to check only my_var first, it can be undefined, too

var xxx = (typeof my_var !== 'undefined' && my_var.property !== 'undefined') ? my_var.property : 'fu';

Upvotes: 3

solendil
solendil

Reputation: 8458

Evaluation of my_var.property fails because my_var is null or undefined. Enhance your code like this:

var xxx = (my_var && typeof my_var.property !== 'undefined') ? my_var.property : 'fu';

Upvotes: 2

Joachim Sauer
Joachim Sauer

Reputation: 308031

Your code checks if the type of my_var.property is undefined. But that can't be checked because the type of my_var itself is already undefined.

Upvotes: 5

Related Questions