Lesson 63 +15 XP

IIFE and Strict Mode

IIFE and Strict Mode

Two more useful function topics: IIFEs run right away, and strict mode makes code safer.

What is an IIFE?

An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it is created:

(function() {
  console.log("Runs immediately");
})();

Why use an IIFE?

  • Run code immediately without polluting the global scope.
  • Create a private scope for variables.
  • Avoid name clashes with other code.

Strict mode

Strict mode catches common mistakes and forbids unsafe actions:

"use strict";

Put it at the top of a script or function.

What strict mode fixes

  • Prevents using undeclared variables.
  • Throws errors on silent failures.
  • Removes dangerous features.
"use strict";
x = 3.14; // Error in strict mode (x is undeclared)

TL;DR

  • An IIFE runs immediately and creates its own scope.
  • IIFEs avoid global scope pollution.
  • "use strict" catches common mistakes.
  • Strict mode forbids undeclared variables.