nktkarnany
nktkarnany

Reputation: 53

variable in jquery giving Uncaught ReferenceError when defined without var

A piece of code from my javascript file

$(document).ready(function(){
    gsdk.init();
});

// Note: No var in the prefix of gsdk and it is also declared only here
gsdk = {
    init : some function...
}

When I add this javascript file in html page and run, it gives

Uncaught ReferenceError: gsdk is not defined(…)

Upvotes: 0

Views: 126

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

That code is relying on The Horror of Implicit Globals¹, where assigning to an undeclared identifier creates a global variable.

To get the error you've described, the ready "event" would have to have already fired before your code is run, because jQuery's ready feature is chaotic: If the page is already ready, it calls its callback synchronously; if not, it calls it asynchronously.

If it were calling the callback asynchronously, you wouldn't be getting an error, because the code assigning to gsdk would have run before the code in the callback, creating the global and giving it its value.

In any case, the fix is:

  1. Declare gsdk, don't rely on the horror of implicit globals, and

  2. Move the initialization of it above your ready code, so that if your ready callback is called synchronously, gsdk is initialized and ready for use.

E.g.:

// 1. Declare the variable, don't rely on The Horror of Implicit Globals.
// 2. Make certain it has its value before setting up your `ready` callback, since
//    apparently you're doing this when the page is already ready.
var gsdk = {
    init : some function...
};

$(document).ready(function(){
    gsdk.init();
});

¹ (That's a post on my anemic little blog.)

Upvotes: 4

Geeky
Geeky

Reputation: 7498

You have syntax error .It should work

Though gsdk is a global variable here ..Not declaring with var should not a problem,but it would create a variable on the global object i.e., window.gsdk/gsdk is same here and even you are declaring gsdk it after invocation it does not throw error because variables are hoisted your code is similar to this below

var gsdk;
$(document).ready(function(){
    gsdk.init();
});

gsdk = {
    init : function(){
       alert("hi");
     }
}

$(document).ready(function(){
    gsdk.init();
});

gsdk = {
    init : function(){
       alert("hi");
     }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions