JQuery: variables declared inside $ (document) .ready (); Global? And when can global errors be avoided?

The concept of globals begins to harden. Any variable outside a function is global, correct? If the variables are contained inside $(document).ready( function() { *code* } ); are considered global?

I found a way to bypass the commonly used array into a function that uses the specified array, but now I essentially use my HTML content as my global ones, if that makes sense (for example, using the text inside the div and passing it into the function). Is this how people usually constantly change / often refer to variables?

If they are not global, should I include variables inside functions to develop good practice?

+6
source share
2 answers

No, they are considered locally within the function.

Check this out for the JavaScript scope : fooobar.com/questions/163 / ...

Variable variables through functions are good practice, especially if you ever want to run your code with minimizer .

+4
source

The variables contained in $(document).ready are not global. When you declare a variable in a function, its scope is a function, then the variable will no longer exist after the function ends.

 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 the global variable as much as you can. Do not enter into the creation of a “god object” containing everything you need, your code will just be more difficult to read and understand.

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

+3
source

All Articles