Tarik
Tarik

Reputation: 1897

JQuery: Are variables declared inside $(document).ready(); globals? And when can globals be avoided?

The concept of globals is starting to solidify. Any variable outside of a function is a global, correct? If variables are contained within $(document).ready( function() { *code* } );, are they considered global?

I figured out a workaround to put a frequently used array into the function that uses said array, but now I am essentially using my HTML content as my globals, if that makes sense (for example, using text inside a div and passing it into a function). Is this how people typically go about constantly changing/often referenced variables?

If they are not globals, should I still enclose the variables inside functions to develop good practice?

Upvotes: 6

Views: 5670

Answers (2)

Mordhak
Mordhak

Reputation: 2656

Variables contained in $(document).ready are not global. When you declare a variable in a function, its scope is the function, then the variable won't exist anymore once the function end.

var myGlobal = "foo";

$(document).ready(function(){
    var myVar = 42; // myVar will only exist in this scope
    $.myVar = 42; // $.myVar will be accessible anywhere since you have access to '$' object
    // care, this variable will be accessible anywhere
    // if you declare a variable with the same name but omit to add the "var" first, it will work without any error (unless you have "use strict")
    myGlobal = "bar";
});

Avoid global variable as much as you can. Don't fall in creating a "god object" containing all you need, your code would just be harder to read and understand.

You can take a look at "use strict" too.

Upvotes: 3

adamb
adamb

Reputation: 4883

No, they're considered locally scoped inside the function.

Check this out for JavaScript scoping: https://stackoverflow.com/a/500459/1538708

Scoping variables via functions is good practice, especially if you ever want to run your code through a minimizer.

Upvotes: 4

Related Questions