Anonymous Functions and IIFE (Immediately Invoked Function Expressions) with JavaScript

Daphne Watson
2 min readFeb 8, 2016

Quick Recap: A function is a block of code created to perform a specific task when it is run.

Here’s an example of a declared function being called.

//declaring the function

function addNumbers(num) {

return num + num };

addNumbers(4); //calling the addNumbers function

The result of calling this addNumbers function is 8. I called the number 4 in the addNumbers function, producing the result 4 + 4 = 8.

What are function expressions? Function expressions occur when a function is placed where an expression would be, then is treated as an expression. Functions like these usually have no name. The function name is not used in function expressions to create something called anonymous functions.

An anonymous function is also referred to as a function literal. This type of function is useful for handling events, like .onload() and .onclick().

The previous addNumbers function is written below as an anonymous function. This function can be similarly called, like any other function.

//declaring the function

var addNumbers = function(num) {

return num + num; };

addNumbers(4) //calling the function, result is 8 again.

IIFE (known as Immediately Invoked Function Expressions) are functions that do not have a name as well. They only run once when the interpreter runs into it.

(function() {

var addNumbers = 4 + 4;

return addNumbers;

})();

The set of matching parenthesis after return addNumbers tell the interpreter to immediately run this function. The outermost parenthesis before the function keyword and at the end of the function are grouping operators, telling the interpreter to make this function an expression.

A few helpful reasons to use anonymous functions and IIFE in your code:

  1. to perform a task for event handlers, listeners, and callbacks — anonymous functions
  2. to maintain data privacy — IIFE

3. to use as an argument when a function is called — anonymous functions & IIFE

4. prevent conflicts between script files that could have the same variable names — anonymous functions & IIFE

--

--