4

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?

messivanio
  • 2,263
  • 18
  • 24
bob
  • 859
  • 1
  • 8
  • 16

9 Answers9

5

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.

Covar
  • 901
  • 1
  • 7
  • 15
4

My response is regarding the Global variables. As others have also mentioned, your global variables can be used/accessed by every scripts that you load into the page(yours or other libraries). Also note that when using javascript in a browser, your self defined variables/functions is under the "window" object.

Instead of creating a lot of global variables/functions what might also be an option is to create one application-wide global variable. You can then add other global elements(variables and even functions as properties to this one object as needed). You can take this further and create sub properties for each specific task. This would help keep the code clean and also make it easier to understand for others looking at your code by providing a kind of a sub-grouping.

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 the 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 might not be too bad but using it within a function is definitely confusing(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 thoroughly) and can lead to unpredictable results. Javascript has two scopes "function level" and "global" and if you do not use the 'var' keyword within a function, any variable you define is created in the global scope though your assignment might be within a function. A variable created as such is now open to access/manipulation by any piece of code across your application.

You can try to simulate a block-scope in javascript by using a Immediately Invoked Function Expressions (IIFE). I recently got introduced to this term.

Check-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 would 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}
PJR
  • 443
  • 4
  • 9
3

If this is a concern at all then you can just wrap your scripts in

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

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

By writing ab = $('#div32'); you will be setting the first ab that javascript encounters to $('#div32'); This could be declared already or you'll be creating it when you try to set it. This isn't a security problem as much as it is a stability problem.

In terms of commas vs semicolons, you're not going to see a difference except for perhaps a slight decrease in the amount of data going down the wire.

var foo = 1, bar = 2;

is functionally the same as

var foo = 1;
var bar = 2;

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

var foo = 1; bar = 2;

This will set variable foo inside function scope, and also create/modify variable bar in global scope (depending on whether or not bar already exists)

Jacob Duval
  • 539
  • 4
  • 14
2

A very good question, because many people will have encountered issues with JavaScript variable scope. Initially, your first assumption should always be to avoid global variables.

Why? This is due to scope. Any variables defined at a global level are subject to being overwritten. So any JavaScript running in your program, being written by yourself or otherwise, will have access to that variable. Worse still, they can be overwritten during loop iterations and so on, causing very odd behaviour (that can be very hard to debug).

Firstly, I suggest you run through the example on this page. It will give you a really nice idea / refresher on what the scope actually means, the relevance of the var keyword, and the potential nasties you can encounter.

Then, it's always worthwhile asking if a variable really needs to be global, and if that fits with the design of your program. I've no doubt there will always be some cases where global variables make sense... but on the whole they can and should be avoided.

EDIT: It's probably too generic to say that on the whole you can pick a different model. However, there have been some comments here which say that if you are writing a small isolated piece of code, then it doesn't matter. This is the bit I disagree with really... You can never fully predict where and how your code will end up getting used in a production system, and not accounting for a potential headache like global variables at the start is not good practice.

Nick
  • 2,285
  • 2
  • 14
  • 26
1

In B/S structure, "global" means 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 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?

Yes.When they can access window object (they always can), they can use "global variables" too, possibly cause bugs as well.

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

Yes.Variables without the var become window scope whereever codes are. Like variale "bc" above.

can I just use variables then for these as well?

Yes.Just doesn't make any sense except for short cut.

I agree with other guys on "commas".

At last,

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

In my opinion, It is not good. But "ok" or not depends on your needs.

Like @Covar said,

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 ...

You should take a look at this too.

Community
  • 1
  • 1
Clxy
  • 505
  • 1
  • 5
  • 13
1

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);
Community
  • 1
  • 1
Mehdi Karamosly
  • 5,388
  • 2
  • 32
  • 50
0

Let me be the first to say, that I do not necessarily have a great deal of JavaScript experience. However, in other languages, (and I'm assuming this is still the case with JavaScript), this is extremely poor code practice.

Variables should be scoped to only the funcitons/modules/classes/etc. that need to use them. If you find yourself continously having to use global scope to pass data around, you are probably doing something wrong.

It'sPete
  • 5,083
  • 8
  • 39
  • 72
0

The main problem with global variables is that you could possibly overwrite other variables or have them overwritten by other libraries. It is always better to avoid cluttering the global scope. For instance, JQuery puts everything into a single variable (function) and takes advantage of closures and such to access things.

As far as commas and semicolons. Semicolons are optional in javascript but definitely recommended for various reasons (like clarity). Using commas when declaring variables is just a short cut to declaring them one by one.

Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
0

I agree with PJR and I am also using code as given below.

var myApplicationModule = {};

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

In case, if you want to use these variables throughout your application or in many modules then you may create a common js file say common.js and include this code in common.js file. You can include this file where ever you need this code.

Thanks, Krishan

Krishan Babbar
  • 766
  • 1
  • 7
  • 17