Global and Local Variables in JavaScript

Hi there, today I’m going to show how you can create global and local variables in JavaScript and also try to explain why you should try to avoid creating global variables in your code, of course I’m not saying that you can’t use it, I’m only saying that if you can find another solution that will use local variables, then you should go for it, but sometimes we know that using global it’s the only way, so try to use it wisely. That’s the best advice I can give you.

I know that a lot of developers think it’s really convenient to create global variables because it’s “THERE” you can always access it. But the problem is, they are created in the moment your code is loaded and it doesn’t matter whether you use it or not it will stay in the memory until your page is closed, in other words you’re wasting resources that can be used for other things, on the other hand local variables are created when the scope (method) they belong is invoked and assigned to be destroyed by the garbage collector right after its execution. As your application grows and become more complex you have to consider all these small details.

Creating global variables

// Right way to declare a global variable.
var AppName = "MyCoolApp";
// It works but it's not a good practice to declare like this.
Version = 1;

Accessing global variables

function CallingGlobal()
{
   // Global.
   alert(AppName + " " + Version); // Result -> MyCoolApp 1
   Version = 2;
   alert(AppName + " " + Version); // Result -> MyCoolApp 2
}

Accessing global and local variables

function CallingLocal()
{
   // Local.
   var Version = 3;
   alert(Version); // Result -> 3
   // Global.
   alert(AppName + " " + window.Version); // Result -> MyCoolApp 2
}

I suggest to do like this:

function CallingMethods()
{
   alert(GetAppName() + " " + GetVersion());
}

function GetAppName()
{
   return "MyCoolApp";
}

function GetVersion()
{
   return 1;
}

Thank you for your time and feel free to leave any comments or questions.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.