3

Possible Duplicate:
How to check a not defined variable in javascript
Determining if a javascript object has a given property

In my beforeSend function i have this

$.myloader.show();

But some scripts dont have that element so my this line gives me error

$.myloader.show(); gives me error that $.myloader does not exists

How can i do something like

if($.myloader exists)
$.myloader.show();
Community
  • 1
  • 1
Mirage
  • 30,868
  • 62
  • 166
  • 261
  • Or http://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript?rq=1 (and other links visible at the right...) – Denys Séguret Oct 11 '12 at 07:17
  • try { some_var.xxx.xxx.xxx x = 't'; }catch(e){ x = 'f'; } console.debug(x); – Ruthe Sep 11 '15 at 07:56

6 Answers6

5

The most generic and solid solution is :

if (typeof $.myloader != 'undefined') {

If you're sure your variable can't hold anything else than a function or undefined, you might use

if ($.myloader) {

But do this only when you're sure of the possible values because this test also match false, 0 and ''.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

You can do it as folllow...

if(typeof $.myloader != 'undefined')
{    // your code here.  }; 
Amol Kolekar
  • 2,307
  • 5
  • 30
  • 45
0

Undefined values are 'falsey', and evaluate to false in an if statement, so all you need is:

if( $.myloader )
    $.myloader.show();
nbrooks
  • 18,126
  • 5
  • 54
  • 66
0

Given that jQuery ($) is an object:

if ($.hasOwnProperty('myloader'))
{
    //should work
    //try: $.hasOwnProperty('fn'), it'll return true, too
}

if the myloader object isn't directly bound to the jQuery object, but via one of its prototypes:

if ('myloader' in $)
{
    //works, like:
    if ('hasOwnProperty' in $)
    {//is true, but it's not a property/method of the object itself:
        console.log($.hasOwnProperty('hasOwnProperty'));//logs false
    }
}

You can check for the methods you want to use in the same way:

if ('myloader' in $ && 'show' in $.myloader)
{
    $.myloader.show();
}
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • `$` is actually a function, but of course also inherits from `Object`... in the end, everything does (apart from `Object.create(null)`), so it should not really matter what `$` is. – Felix Kling Oct 11 '12 at 07:20
  • @FelixKling, yes, it's a function, but functions are first class objects. Tomato - tomato, really – Elias Van Ootegem Oct 11 '12 at 07:23
0

You can do this even more shortly:

$.myloader.show() ? console.log('yep') : console.log('nope');

Or:

$.myloader.show() || console.log('fail');
happyCoda
  • 418
  • 2
  • 2
0

If you want it short, you can also do it like this:

$.myloader && $.myloader.show();

The first operand (before the &&) is called a guard. However some people argue that this is not readable and safe enough, so you might want to use the if (typeof ...) solution.

Felix
  • 769
  • 1
  • 7
  • 8