Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Why Global Variables Shouldn’t Be Very Global

DZone 's Guide to

Why Global Variables Shouldn’t Be Very Global

A discussion of global vs. local variables in JavaScript and and how to properly use global functions in your JS code.

· Web Dev Zone ·
Free Resource

Global variables

One of the biggest blunders a JS developer can do make while writing code is declaring unnecessary global variables. Global variables are extremely helpful for programmers, but if they are not used carefully, they can rob the speed and efficiency of any browser.

Short Note

There are mainly two types of variables that are used in JS: local and global. Local variables are defined and used within a function, whereas global variables are defined for the function window. In short, until the code doesn’t terminate, global variables will be present, lurking in the background.

Effect on Memory

Variables storing feeble data won’t be too critical, however, if you store a lot of data on it it’ll choke your bandwidth and definitely threaten the page efficiency. Too much data stored as cache slows the speed of your browser, resulting in high latency. Caches are a website’s data that are stored and used when you revisit the site time and again.

Solution

We can’t deny the usefulness of global variables, however its best to try using local variables and use globals ones only in situations where it can’t be helped. However, it’s important to change the value of the variables to NULL after using.

function Avengers() {    
  var hero = "Nick Fury";
}

Accidental global variables are created when you assign a value to a variable that hasn’t been declared, by default it will be a Global variable.

function Avengers() {            
  hero = "Nick Fury";
}

“Use strict” is a brilliant way to keep global variables in check; just writing this command will solve half of your problems. Mostly used by developers, it doesn’t allow for menacing accidental variables by giving an error if the variable hasn’t been declared.

<h2>
	Global "use strict" declaration.
</h2> 
<script> "use strict"; 
	Avengers();   
	function Avengers() {
		hero = "Nick Fury";                    
// This will cause an error (hero is not defined) 
    } 
</script>

memory leakage due to global variable

Conclusion

The use of global variables isn’t that global anymore. In the next post, we will further explore memory leakage problems.

Topics:
javascript ,global variables ,memory leaks ,web dev ,javascript tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}