Search⌘ K
AI Features

Discussion: The Fun-ction

Explore Immediately Invoked Function Expressions or IIFEs, a JavaScript pattern that creates isolated scopes and executes functions instantly. Learn different syntax forms and understand how they prevent global namespace pollution while enhancing code organization.

Verifying the output

Now, it’s time to execute the code and observe the output.

Javascript (babel-node-es2024)
!function() {
const name = "john";
const age = 20;
}();
const capitalizedName = name[0].toUpperCase() + name.slice(1);
console.log(capitalizedName);

Understanding the output

The problem in this code is that name has what we call function scope, meaning it’s accessible only within that function. So, if we attempt to use the value of name out of the function, we’ll encounter a reference error because name is undefined in the outer scope.

Immediately invoked function expression (IIFE)

The function in this puzzle is known as an immediately invoked function expression (IIFE) ...