To learn Javascript I am building a simple Single-Page Application. It is a basic slideshow app that needs only to process some basic settings and execute some behaviors. The basic structure of my code is thus:

var settings = { ... };

function initStartPage() { ... };
function initSlideshow() { ... };
function settingsHandler() { ... };
function doSomething() { ... };

... where each function needs to access and possibly modify the data contained in the variable settings.

I'm a little stumped on how I might be able to structure this without using global variables or unnecessarily complicated constructs. I am used to programming in Java or C, where variables for small apps can live comfortably in the main function. The only solution I can think of to get rid of the global scope is simple namespacing:

var namespace = {};
namespace.settings = { ... };

namespace.initStartPage = function() { ... };
namespace.initSlideshow = function() { ... };
namespace.settingsHandler = function() { ... };
namespace.doSomething = function() { ... };

So my questions are:

1. Is this a reasonable solution for a system where many parts will be accessing the same data?

2. Is there a better, more standard solution?

  • All the functions are getting settings directly from the scope that defines them, it just happens to be the global scope? You can pretend there is a void main() { ... } around your code if you like – Caleth Aug 9 at 13:18

Yes, I believe that is the standard approach if you want to have PUBLIC (namespace) variables. But to make private namespace variables, the usual approach is to use a closure (example using closure for private data)

Or, since you are learning, please consider using typescript, which directly supports private data members.

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.