I like to be minimalist with my code, so is it OK 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 with that is that there is no encapsulation, and the code is a bit messy, a better way to do it is to create a global object that will contain all your needed variables like below :
instead of :
ab = $('#div32');
bc = 1000;
you would 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 can hold functions as well :
myData.sumTwoVariable = function(a,b){return a+b;}
A nice article talking about functions within objects : Different ways to add functions to Javascript object
Does Global mean that just any of the code in that specific file can
use those variables? Or does it mean that if I am using a plugin which
has a "separate" js file , that that file can use my global variables
as well, and possibly cause bugs?
If they are declared in the global scope (with or without using var
, no difference) then yes they would be accessible in the other js files, and Yes it could possibly cause bugs and issues if the same variable name is used in other javascript files at the global scope as well, in this case your variable will be overriden and will have the value of the most recent affectation.
This is a nice post if you want to read more : Javascript: Scope of a Variable across different Javascript files
Is there security threats then to writing variables like this, without
the var
var
is only used to specify 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
these as well?
Yes you can.
zy = $(window); yy = $(document); Also, whats the difference between
putting commas after your variables (except the last one) then putting
semicolons after each one? Does it have an effect on anything?
No difference.
This would work:
zy = $(window); yy = $(document);
and this too :
zy = $(window), yy = $(document);