Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to place all JS / jQuery variables at top of file? Global variables?

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?

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?

Is there security threats then to writing variables like this, without the var

ab = $('#div32');
bc = 1000;

Also, can I just use variables then for these as well?

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?

like image 850
bob Avatar asked Dec 05 '22 10:12

bob


1 Answers

Global variables are scoped to the program, so if you pull in other javascript that also uses the same global variable names you will almost certainly encounter bugs.

If you're writing something fairly small there's certainly nothing (technically) wrong with declaring all of your variables as global, but if you're writing something that's going to grow it might be to your benefit to use some form of module pattern to provide another level of scope to your variables and minimize the use of Globals. With a module pattern you can usually reduce your global variables down to the Module namespace, with what would normally be globals, scoped only up to the module.

like image 152
Covar Avatar answered Jan 19 '23 00:01

Covar