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:
var AGLOBALNAMESPACENAME = {};
AGLOBALNAMESPACENAME.user = {
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.