Can I put all the JS / jQuery variables at the top of the file? Global variables

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?

Does Global mean that only any code in this particular file can use these variables? Or does this mean that if I use a plugin with a "separate" js file, this file can also use my global variables and possibly cause errors?

Are there any security risks for writing such variables without var

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

Also, can I just use variables then for them?

 zy = $(window); yy = $(document); 

Also, what is the difference between putting commas after your variables (except the last one), and then with a comma after each? Does it affect anything?

+4
source share
9 answers

If this is a problem at all, you can simply wrap your scripts in

 (function(){ var ab = $('#div32'); var bc = 1000; })() 

and then they will be declared in the scope of functions instead of the global scope.

Writing ab = $ ('# div32'); you will set the first ab that javascript encounters with $ ('# div32'); This could be declared already, or you will create it when you try to install it. This is not a security issue, but a stability issue.

In terms of commas and semicolons, you will not see any differences, with the possible exception of a slight decrease in the amount of data going through the wires.

 var foo = 1, bar = 2; 

functionally coincides with

 var foo = 1; var bar = 2; 

Edit: As Joe pointed out, there is a third case that I should have mentioned.

 var foo = 1; bar = 2; 

This sets the foo variable inside the function area, and also creates / modifies the bar variable in the global area (depending on whether the bar already exists)

+3
source

Global variables are tied to the program, so if you use another javascript that also uses the same global variable names, you will almost certainly encounter errors.

If you write something rather small, there is nothing (technically) wrong with declaring all your variables global, but if you write something that will grow, it may be useful for you to use some form of template module to provide another level of coverage for your variables and minimize the use of globals. Using a module template, you can usually reduce global variables to a module namespace, with what will usually be global, only with a module.

+5
source

My answer is about global variables. As mentioned in other sources, your global variables can be used / available for each script that you upload to the page (yours or other libraries). Also note that when using javascript in a browser, your self-defined variables / functions are under the "window" object.

Instead of creating a large number of global variables / functions, which may also be an option, you need to create one global application variable. Then you can add other global elements (variables and even functions as properties for this single object as needed). You can do this further and create additional properties for each specific task. This will help keep the code clean, as well as simplify the understanding for others viewing your code by providing a kind of subgroup.

As an example

 var myapp = {}; //creating a global mathmodule property under myapp that does all the math related work myapp.mathmodule = {}; myapp.mathmodule.myvariable1 = 7; myapp.mathmodule.myvariable2 = 3; myapp.mathmodule.add = function() { myapp.mathmodule.sumvalue = myapp.mathmodule.myvariable1+myapp.mathmodule.myvariable2; }; myapp.mathmodule.substract = function () { myapp.mathmodule.differencevalue = myapp.mathmodule.myvariable1 - myapp.mathmodule.myvariabl2; }; //creating a global logmodule property under myapp that does all the logging work myapp.logmodule ={}; myapp.logmodule.defaultmessage = "Default Values"; myapp.logmodule.logresults = function () { console.warn('myapp.mathmodule.sumvalue:'+window.myapp.mathmodule.sumvalue); console.warn('myapp.mathmodule.sumvalue again:'+myapp.mathmodule.sumvalue); console.warn('myapp.mathmodule.differencevalue:'+window.myapp.mathmodule.differencevalue); console.warn('myapp.mathmodule.differencevalue again:'+myapp.mathmodule.differencevalue); }; myapp.logmodule.logdefaultvalues = function () { console.log(myapp.logmodule.defaultmessage); console.log('myapp.mathmodule.myvariable1:'+myapp.mathmodule.myvariable1); console.log('myapp.mathmodule.myvariable2:'+myapp.mathmodule.myvariable2); }; 

// you can use functions like

 myapp.mathmodule.add(); myapp.mathmodule.substract(); myapp.logmodule.logresults(); myapp.logmodule.logdefaultvalues(); 

Creating a new variable without var at the top of the file may not be too bad, but using it inside a function is definitely confused (anyone else reading your code will not be sure if you really intended to create a global variable from your function without reading our code ) and can lead to unpredictable results. Javascript has two areas of “function level” and “global”, and if you do not use the keyword “var” inside a function, any variable you define is created in the global area, although your purpose may be within the function. Now the variable created as such is now open for access / manipulation by any piece of code in your application.

You can try to simulate the block area in javascript using expressions with instant call function (IIFE). I recently introduced this term.

Get out more at http://en.wikipedia.org/wiki/Immediately-invoked_function_expression and http://benalman.com/news/2010/11/immediately-invoked-function-expression

 //if the code below followed the code at the top //anything defined within this function is not exposed elsewhere (function () { var myapp = "Trying to overide the global myapp value"; console.log("Testing myapp value in an iife:",myapp); console.log('Global myapp still accessible via window object:',window.myapp); }()); console.log('myapp value outside of iife is the global value:',myapp); 

The output will be

 Testing myapp value in an iife: Trying to overide the global myapp value Global myapp still accessible via window object: Object {mathmodule: Object, logmodule: Object} myapp value outside of iife is the global value: Object {mathmodule: Object, logmodule: Object} 
+4
source

A very good question, because many people will run into problems with the scope of JavaScript variables. Initially, your first guess should always be to avoid global variables.

Why? This is due to coverage. Any variables defined at the global level are subject to rewriting. Thus, any JavaScript running in your program, written independently or otherwise, will have access to this variable. Worse, they can be overwritten during loop iterations, etc., causing very strange behavior (which can be very difficult to debug).

First, I suggest you follow the example on this page . This will give you a really nice idea / update what the scope really means, the relevance of the var keyword and the potential nasty things you might encounter.

Then you should always ask yourself if the variable should really be global, and if it matches the design of your program. I have no doubt that there will always be cases when global variables make sense ... but in general they can and should be avoided .

EDIT: Perhaps too general to say that overall you can choose a different model. However, there were some comments that said that if you write a small, isolated piece of code, then it does not matter. This is the fact that I do not agree with reality ... You can never fully predict where and how your code will ultimately be used in a production system, and not take into account potential headaches, such as global variables at the beginning, not a good practice.

+2
source

In the B / S structure, "global" means a window.

Example

 ab = $('#div32'); $(window).load(function() { console.log(window.ab.text());// text of div32. console.log(window.ab === ab);//true bc = 1000;//Become global. }); setTimeout(function() { console.log(window.bc);// 1000 }, 1000); 

Does Global mean that only any code in this particular file can use these variables? Or does this mean that if I use a plugin with a "separate" js file, this file can also use my global variables and possibly cause errors?

Yes. When they can access the window object (they can always), they can also use "global variables", possibly also causing errors.

Are there any security risks for writing such variables without var

Yes. Variables without var become the window pane. Like variale "bc" above.

Is it possible to just use variables, and then for them?

Yes. It just does not make any sense, except for a short cut.

I agree with the other guys in commas.

Finally,

Can I put all the JS / jQuery variables at the top of the file? Global variables

In my opinion, this is not good. But “good” or not depends on your needs.

Like @Covar said

If you write something rather small, then, of course, there is nothing (technically) wrong with declaring all your variables global, but if you write something that will grow ...

You should also take a look at this one .

+1
source

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); 
+1
source

Let me be the first to say that I do not have much experience with JavaScript. However, in other languages ​​(and I assume this is still the case with JavaScript), this is an extremely bad code practice.

Variables should be limited only to funcitons / modules / classes / etc functions. who should use them. If you constantly use the global scope for data transfer, you are probably doing something wrong.

0
source

The main problem with global variables is that you could overwrite other variables or overwrite them with other libraries. It is always better to avoid cluttering the global realm. For example, jQuery puts everything in one variable (function) and takes advantage of closure, etc. For access to things.

As for commas and semicolons. Semicolons are optional in javascript, but are definitely recommended for various reasons (e.g. clarity). Using commas when declaring variables is simply a shorthand to declare them one at a time.

0
source

I agree with PJR and I also use the code as shown below.

 var myApplicationModule = {}; myApplicationModule.isIE = false; myApplicationModule.populateErrorsData = function() { } 

In case you want to use these variables throughout the application or in many modules, you can create a common js file, for example common.js, and include this code in the common.js file. You can include this file where you need this code.

Thanks Krishan

0
source

Source: https://habr.com/ru/post/1488193/


All Articles