Maintainability - Lessens the dependency on other parts of the codebase
Namespacing - Unrelated code shares global variables
Reusability - Ability to reuse modules
Module patterns uses an IFFE (Immediately Invoked Function Expression) to return an object
(function(){
//salaries are private
var salaries = [1000, 2000, 5000, 7000, 10000];
var avgSalary = function(){
var total = 0;
for(var i = 0; i<salaries.length; i++){
total += salaries[i];
var avg = total/salaries.length;
}
return avg;
}
console.log(avgSalary()); //5000
}());
var workerSalaries = (function(){
var salaries = [10, 20, 30, 40, 50];
return {
median: 30,
maxSalary: function(){
var max = Math.max(salaries[0], salaries[4]);
return max;
}
}
}()); //50
var openBank = (function(){
//private
var name = 'Jon Smith';
var acctNo = 12345;
var obj = {};
//public var
obj.balance = 300000;
//public method
obj.deposit = function(n){
var newBal = this.balance + n;
return newBal
}
return obj;
}())
console.log(openBank.balance)
console.log(openBank.deposit(1))
console.log(openBank.acctNo)
var workerSalaries = (function(){
var salaries = [10, 20, 30, 40, 50];
var maxSalary = function(){
var max = Math.max(salaries[0], salaries[4]);
return max;
}
return {
maxSalary: maxSalary
}
}())
console.log(workerSalaries.maxSalary()) //50