- variables by default have an implied global scope
- functions by default have an implied global scope
- all objects inherit from the native / built-in global objects
In relevance to this code, each request will increase the global variable gbl by 1, as seen in the screenshot below for two different requests. In a PHP script such a model would only show 1 for every request.
So, what could go wrong from security perspective? Short answer - it depends, on the context and sensitivity of a global variable or function. An attacker could exploit this behavior to her benefit to achieve desired effects. What could those be,
- as a web user, could bypass logic flows
- a malicious library could over-ride native, built-in or known objects, variables, functions to adversely impact sensitive code base/libraries
- in a shared coding environment, an inexperienced developer could unintentionally over-ride native, built-in or known objects, variables, functions - adversely impacting sensitive code base/libraries
So what's the defense? Unless really needed, always define your functions, variables, as local, as shown in the screenshot below.
Now you get the desired effect as in PHP. Each request now shows gbl as 1. For potential rogue/malicious libraries - audit them! JSLint (though a bit noisy) is a good bet.