Skip to content

Instantly share code, notes, and snippets.

@santiago-puch-giner
Created May 5, 2016 22:21
Show Gist options
  • Save santiago-puch-giner/7a307e5d5fb0218e187281183e01ad4e to your computer and use it in GitHub Desktop.
Save santiago-puch-giner/7a307e5d5fb0218e187281183e01ad4e to your computer and use it in GitHub Desktop.
Immediately Invoked Function Expression in Javascript
// Snippet for IIFE
// An IIFE (Immediately Invoked Function Expression) is a JavaScript function
// that runs as soon as it is defined. They can be written in different ways,
// though a common convention is to enclose both the function expression and
// invocation in parentheses.
var sulphuricAcid = (function(){
var corrosive = true;
var pH = 2;
return {
property: function(){
console.log(`Corrosive : ${corrosive}`);
console.log(`pH acidic : ${pH < 7}`);
}
};
})();
console.log(sulphuricAcid.pH); // Outputs: undefined, we can't access private properties.
sulphuricAcid.property();
// Another example
var captcha_check = (function() {
var actual_captcha = Math.floor(Math.random(100)*Math.pow(10, 5));
return {
check: function(guess) {
if(guess === actual_captcha) {
console.log("You have written it correctly.");
}
else {
console.log("You have written it incorrectly.");
}
}
};
})();
var bot = captcha_check.actual_captcha;
captcha_check.check(bot); // Expected output: You have written it incorrectly
console.log(bot); // Expected output: undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment