The global object and local variables
JavaScript’s global object is the container of all global variables. Any top-level variable of any compilation unit will be stored in the global object. The global object is one of the worst parts of JavaScript when it is not used correctly, as it can easily become bloated with unneeded variables and can be unknowingly abused by developers when JavaScript default behavior is heavily relied upon. Here are two examples of such misuse:
- When running a simple code such as
total = add(3, 4);
, you are, in fact, creating a property namedtotal
in the global object. This is not a good thing for performance as you might keep a lot of variables on the heap while most of them are only required at a certain moment of an application's execution. - When neglecting to use the
new
keyword in order to create an object, JavaScript will execute an ordinary function call and will bind thethis
variable to the global object. This is a very bad thing, not only for security reasons...