const GokuldhamSociety = (function() {
// Private variables
let residents = [];
let societyFunds = 100000;
const secretCode = "TMKOC2024";
// Private functions
function validateResident(name) {
return name && name.length > 0;
}
// Public API (returned object)
return {
addResident: function(name) {
if (validateResident(name)) {
residents.push(name);
return `${name} added to society!`;
}
return "Invalid resident name!";
},
getResidents: function() {
return [...residents]; // Returns copy, not original
},
collectFunds: function(amount) {
societyFunds += amount;
return `Collected $${amount}. Total funds: $${societyFunds}`;
}
};
})(); // IIFE - Immediately Invoked Function Expression
console.log(GokuldhamSociety.addResident("Jethalal"));
console.log(GokuldhamSociety.addResident("Babita"));
console.log(GokuldhamSociety.getResidents());
console.log(GokuldhamSociety.collectFunds(5000));
// โ No access to private data
console.log(GokuldhamSociety.residents); // undefined
console.log(GokuldhamSociety.societyFunds); // undefined
console.log(GokuldhamSociety.secretCode); // undefined