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.
0
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…
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.
3