Saturday, 22 December 2018

JavaScript: Immediately invoked function expressions

An Immediately invoked function expression (IIFE) is a function, that is invoked as soon as it is defined.

Syntax
(function () {
    statements
})();

app.js
(function () {
	console.log('I will execute immediately')
})()

Run app.js, you will see below messages in console.

I will execute immediately

You can writhe the same snippet using named functions like below.
(function sayHello(){
         console.log('Hello World')
}())

You can even pass arguments to IIFE.

app.js
(function (name, age){
	console.log(`Hello ${name}, you are ${age} years old`)
}('krishna', 10))

Run app.js, you can see below messages in console.
Hello krishna, you are 10 years old

You can assign the return value of IIFE to a variable.

app.js

var message = (function (name, age){
	return `Hello ${name}, you are ${age} years old`
}('krishna', 10))

console.log(message)

Output
Hello krishna, you are 10 years old




Previous                                                 Next                                                 Home

No comments:

Post a Comment