For some time I’ve been finding myself coding more JavaScript instead of server-side code. And I like it! But that aside, I want to ask you: do you have a file and object-wise layout for your JS code?
I’ve got my hands on a bigger project. And I thought: what path will I choose for name spaces of the objects and directory structure?
The layout
This time I will go with something Java-like. For example, my system error message handler would be System.ErrorMessage, so to show an error I would need to call
System.ErrorMessage.show('This is an error');
The folder structure will be only one directory deep – the first name space being the directory. This differs from the Java approach because in Java there would be a N deep directory tree, N being name spaces of the class (System – 1, ErrorMessage – 2). All other classes will be there as files separated with a dot. Some examples:
- System would lie in JS_DIR/system/system.js
- System.ErrorMessage » JS_DIR/system/system.errormessage.js
- Form.Upload.Ajax » JS_DIR/form/form.upload.ajax.js
- And the list goes on…
Why this one?
I find this clear, simple and attractive. For huge and JS-intensive projects I guess that multi-directory structure is the better way to go because you – the programmer – are more happy to look at more directories with fewer files than vice versa. But for small to almost-big this is a good way of keeping files ordered.
“Why not place the error messenger in a directory called “messages” instead?”, you may ask. I recommend staying focused without trying to reinvent the wheel
The naming should come directly from the class names so that:
- You (or anyone else) can find the files later easy.
- It would be much easier to write code that does class name to file name conversions (for example, caching all required JS files into one or auto-loading missing JS files).
- Everybody does it this way. Well, the smarter ones do. This alone isn’t a good statement, but then look at #1.

Pingback: Project JavaScript string localisation | Web developer Steponas Dauginis' blog