I like to be minimalist with my code, so it's normal to just declare a lot of variables at the very top of the file. I understand that this will make them global?
The only problem is that there is no encapsulation, and the code is a bit messy, the best way to do this is to create a global object that will contain all the necessary variables, as shown below:
instead:
ab = $('#div32'); bc = 1000;
would you use:
myData = { ab : $('#div32'), bc : 1000 }
or alternatively:
myData = {} ; // or = new Object; myData.ab = $('#div32'); myData.bc = 1000;
And to access your global variable you do:
console.log(myData.ab);
And your myData object may also contain functions:
myData.sumTwoVariable = function(a,b){return a+b;}
Good article on functions inside objects: Different ways to add functions to a Javascript object
Does Global mean that any code in this particular file can use these variables? Or does this mean that if I use a plugin that has a “separate” js file that can use my global variables and also possibly cause errors?
If they are declared in the global scope (with or without var , no difference), then yes, they will be available in other js files, and Yes, this can lead to errors and problems if the same variable name is also used in other javascript files in the global scope, in which case your variable will be overridden and will have the value of the most recent affectation.
This is a good post if you want to read more: Javascript: Variable area in different Javascript files
Are there any security risks for writing such variables without var
var used only to indicate a local variable in the scope of a function, please read this article: What is the purpose of the var keyword and when to use it (or omit it)?
ab = $ ('# div32'); bc = 1000; Also, can I just use variables then for they as well?
Yes, you can.
zy = $ (window); yy = $ (document); Also, what is the difference between entering commas after your variables (except the last one), followed by a comma after each? Does it affect anything?
No difference. This will work:
zy = $(window); yy = $(document);
and this too:
zy = $(window), yy = $(document);