I am looking at the following example from MDN on use cases for IIFE's. I don't understand why the IIFE is necessary. Even if I rewrite makeWithdraw as just a function declaration taking in copyBalance as a parameter, the result is the same. I understand this is due to functional scoping and that using IIFE might have some other use cases about global namespace and closures. But what is MDN trying to show us here? Somehow I haven't correctly learned something. Can someone please help me get back on track?
const makeWithdraw = balance => (function(copyBalance) {
let balance = copyBalance; // This variable is private
let doBadThings = function() {
console.log("I will do bad things with your money");
};
doBadThings();
return {
withdraw: function(amount) {
if (balance >= amount) {
balance -= amount;
return balance;
} else {
return "Insufficient money";
}
},
}
})(balance);
const firstAccount = makeWithdraw(100); // "I will do bad things with your money"
console.log(firstAccount.balance); // undefined
console.log(firstAccount.withdraw(20)); // 80
console.log(firstAccount.withdraw(30)); // 50
console.log(firstAccount.doBadThings); // undefined, this method is private
const secondAccount = makeWithdraw(20); // "I will do bad things with your money"
secondAccount.withdraw(30); // "Insufficient money"
secondAccount.withdraw(20); // 0
Have to study your answers more but in response to comment about reproducibility, my apologies, this to what I meant by function declaration:
function makeWithdraw (balance) {
let doBadThings = function() {
console.log("I will do bad things with your money");
};
doBadThings();
return {
withdraw: function(amount) {
if (balance >= amount) {
balance -= amount;
return balance;
} else {
return "Insufficient money";
}
},
}
};
const firstAccount = makeWithdraw(100); // "I will do bad things with your money"
console.log(firstAccount.balance); // undefined
console.log(firstAccount.withdraw(20)); // 80
console.log(firstAccount.withdraw(30)); // 50
console.log(firstAccount.doBadThings); // undefined, this method is private
const secondAccount = makeWithdraw(20); // "I will do bad things with your money"
console.log(secondAccount.withdraw(30)); // "Insufficient money"
secondAccount.withdraw(20); // 0