JavaScript fundamentals / 08
Immediately invoked function expressions
Use an IIFE to run a function immediately after defining it, and avoid a common semicolon pitfall.
On this page
What is an IIFE?
An IIFE, or Immediately Invoked Function Expression, runs as soon as it is defined. It is useful when a function is created for an immediate, one-time call.
Consider this example, which first declares a normal function and then calls it:
const a = 1
function ong(x){
document.write(x + 1)
}
ong(a)
The constant a is one. The function ong accepts x and writes x + 1 to the document. Calling it with a therefore writes 2. When defining and immediately calling a function like this, we can express the same intention with an IIFE.
Two common forms
Here are two ways to turn the example into an immediately invoked expression:
const a = 1;
//ex1: (function{})()
(function (){
document.write(a + 1)
})();
//ex2: (function{}())
(function (){
document.write(a + 1)
}());
The two forms are (function () {})() and (function () {}()). Both wrap a function expression in parentheses and immediately call it. The difference is where the invocation parentheses appear relative to the outer pair.
Be careful with semicolons
If you have worked with C or C++, you will already be familiar with semicolons at the ends of statements. JavaScript permits omitting them in many situations, but a line beginning with an IIFE's ( can accidentally be interpreted as a continuation of the preceding expression.
Terminate the preceding statement explicitly, or otherwise separate the IIFE safely. The original screenshot demonstrates the error caused by failing to do so:

Remember the statement boundary when writing an IIFE.
Moved here from Tistory
I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.
The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.
Original post on Tistory English edition · Aug 30, 2026