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?
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.
And the document is not a Global object, it's a property of the Global window object.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With