0

This question already has an answer here:

I have seen other peoples code and each person has a different way of declaring variables. And I have been told by quite a few people that declaring variables in the Global Scope is wrong.

My question is why is it wrong and what is the correct way of declaring variables while writing any software, application or system.

Thanks in advance.

marked as duplicate by gnat, durron597, user40980, user22815, Dan Pichelman Jul 14 '15 at 20:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

One of the problems of using global variables is that it can lead to conflicts when you use them with other modules that also uses the same variable names and are also declared global in those modules. Say you have a Javascript file call it main.js and in that file are codes where there are global variables A, B and C. Then, your colleague who is also working in the same project as you do creates another Javascript file called main2.js and he too for the sake of example made use of variables A, B, and C yet those variables are for a different purpose in your project. Now, since your application requires both of your modules, you load them up. When, the application is run there are chances that your program will crash due to conflicts of the variables during runtime. The Javascript file that was loaded last will supercede the ones that were loaded first. This is one of reasons why global variables are rarely used. Hope this answer helps...

0

On problem with globally scoped variables is that it can make the understanding of who needs to use that variable or modify it more difficult. It also means that as code grows, there can be collisions in usage of the variable - not simply having the same name for what should be two variables, but separate usages of the same variable in different program flows.

  • 1
    An example would go a long way here... Your answer might be too technical (and possibly too vague) for someone who's at the learning stage where they don't know why global variables are bad. – Robert Harvey Jul 13 '15 at 1:19
  • Thank you for the answer. what you be able to give an example. An example for why global variables are bad and whats the correct way of declaring them. – Lorenzo von Matterhorn Jul 13 '15 at 1:48
  • Rather than restate what has been explained well before, please check out this link as it is good example of global variables being a bad idea in general and how to properly handle them - gist.github.com/hallettj/64478 – Jason K. Jul 13 '15 at 2:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.