• Programming
  • JavaScript

What are self invoking functions?

October 21, 2020 • 1 min read

Also known as Immediately-Invoked Function Expression

I was recently checking out a presentation online and saw the term "self invoking functions". I heard it many times but never really took the time to understand what it is or when it's used, so I decided to learn more about them. Here are some things I found out.

Self Invoking Functions

A self invoking function is a function expression that is immediately invoked.


Here is a conventional example of what this looks like:


1
(function() {
2
console.log('Hello There')
3
})()

The code has two parts:


  1. The function expression:
1
function () { console.log('Hello There') }
  1. The function invocation by adding () to the end.

Running this code, you will see that "Hello There" is immediately logged to the console.


On it's own, the function expression can not exist. This is because the parser would expect a name after the keyword function. In order for the parser to understand that this is a function expression, the convention has been to wrap the expression in parentheses.


However, it turns out, as I read here, in some cases you don't actually need to use the parenthese if you add a unary operator before the function keyword like this:


1
-(function() {
2
console.log('Hi there')
3
})()

It is important to note that prepending unary operators before the function to get it to invoke right away is not a good idea. Other than the fact it makes the code more ambiguous, and it deviates from conventions, it would not work if the function has a return value.


We can use an example to show this:


1
const result = -(function() {
2
return 1
3
})()

What do you think result is? If you guessed -1, you are correct. The function will return 1 since it's immediately invoked, but then the result gets negated, resulting in -1. You probably don't want to do this in your code, especially not product code 😬.


There you have it, an overview of self invoking functions. Stay on the lookout for a post on use cases.