Print Shortlink

Global variables in JavaScript

It’s normal to get caught in the web of global variables, while working with JavaScript. Global variables tend to make the code less readable and maintainable. Douglas Crockford suggests a pattern that can be used to maintain global variables in our code.

Let’s say you have the following code.

var userName = "";
var password = "";
var userType = "";

function loadCredentialsFromLocalStorage(){
 userName = localStorage.getItem("userName");
 password = localStorage.getItem("password");
 userType = localStorage.getItem("userType");

The global variables userName, password and userType variables can be written as:

               userName : "", 
               password : "", 
               userType : ""

function loadCredentialsFromLocalStorage(){
 AGLOBALNAMESPACENAME.user.userName = localStorage.getItem("userName");
 AGLOBALNAMESPACENAME.user.password = localStorage.getItem("password");
 AGLOBALNAMESPACENAME.user.userType = localStorage.getItem("userType");

In the code above, you can create a variable giving it a Global namespace name and have all the ‘actual’ global variables assigned to it. The declaration of the global variables can be moved to a separate file as well. Hence the code becomes lot more readable and easy to maintain.

Page 1 of 1

One Response

  1. fashion style

    Hello There. I discovered your blog the use of msn. This is a very neatly written article. I will make sure to bookmark it and come back to learn more of your useful information. Thank you for the post. I’ll definitely comeback.

Leave a Reply