Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 427
Tarik Avatar asked Dec 20 '12 16:12

Tarik


People also ask

How do you declare a global variable in jquery?

Note that we can declare a global variable in two ways, the first way is declaring a variable outside a function, and the second way is to assign a value to the variable without using a var keyword inside a function that means the variable automatically becomes a global variable.

Is document a global variable?

And the document is not a Global object, it's a property of the Global window object.


2 Answers

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.

like image 108
adamb Avatar answered Oct 21 '22 05:10

adamb


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.

like image 30
Mordhak Avatar answered Oct 21 '22 04:10

Mordhak