Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A very good question, because many people will have encountered issues with JavaScript variable scope. Initially, your first assumption should always be to <em>avoid</em> global variables.</p> <p>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).</p> <p>Firstly, I suggest you run through the <a href="https://gist.github.com/hallettj/64478" rel="nofollow">example on this page</a>. It will give you a really nice idea / refresher on what the scope actually means, the relevance of the <code>var</code> keyword, and the potential nasties you can encounter.</p> <p>Then, it's always worthwhile asking if a variable <em>really needs</em> 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... <strike>but on the whole they can and should be avoided</strike>.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload