What is the purpose of a self executing function in javascript?

It’s all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code.

For example, as mentioned in a comment by Alexander:

(function() {
  var foo = 3;


This will first log 3 and then throw an error on the next console.log because foo is not defined.

Leave a Comment