Is very important how you structure your JavaScript because:
- If done right, it makes code easier to understand for others and yourself when re-visting your own code.
- Having a decided-upon structure helps keeping future code clean and encourages your declared best practices.
- It makes your code testable.
For JavaScript design pattern we are using "Module Pattern", which helps keep the units of code both cleanly separated and well organized.
Each module object is a separate file and is loaded on the page with the help of RequireJS, JavaScript file and module loader.
Here is how a module looks like.
var s, PrimaryNameSpace = { settings : { basicExample: $('.main'), nestedExample : { first: true, second: true, third: true, fourth: true, fifth : ['one', 'two', 'three', 'four', 'five', 'six'] }, foo: 'bar' }, init: function () { s = this.settings; this.nextMethod(); this.anotherMethod(); }, nextMethod: function () { }, anotherMethod: function () { } };
For more about JavaScript module pattern read the How Do You Structure JavaScript? The Module Pattern Edition article.