JS Built-ins
Closuresbeginner

Closures β€” IIFE (Immediately Invoked Function Expression)

πŸ“– Usage Example
const result = (function() {
  const secret = 42
  return secret
})()
result  // β†’ 42
// secret is not accessible outside the IIFE

An IIFE runs immediately and creates its own scope, so inner variables are private and the computed result is exposed only through the return value.

Immediately Invoked Function Expression

An IIFE is a function that runs immediately after being defined, creating its own scope.

Challenge: Write an IIFE that returns a value immediately. The function should execute and return 42 as soon as it's defined.

Example:

const result = (function() {
  return 42
})()
result  // 42
πŸ’‘ Hints (3)
  • β€’ IIFE is a function definition wrapped in parentheses followed by ()
  • β€’ The function executes immediately and returns a value
  • β€’ Useful for creating private scopes