Skip to main content

JavaScript Functions – IIFE and Arrow Function Explained

A JavaScript function is an executable piece of code developers use to bundle a block of zero or more statements.

In other words, a function is an executable subprogram (mini-program).

A JavaScript function is a subprogram because its body consists of a series of statements (instructions) to the computer—just like a regular program.

The instructions in a function's body can be a variable declaration, return call, console.log() invocation, function definition, or any other JavaScript statements.

note
  • A program is a list of instructions written for computers to execute.
  • Unlike other object types, you can invoke a function without storing it in a variable.
  • A JavaScript function is similar to other programming languages' procedures or subroutines.

Why Functions?

Functions provide a way to bundle pieces of code together and reuse them anytime, anywhere, for an unlimited period. This helps you eliminate the burden of writing the same set of code repeatedly.

For instance, alert() is a built-in window function that someone wrote once for all developers to use anytime, anywhere.

Syntax of a JavaScript Function

function nameOfFunction(parameter1, parameter2, ..., parameterX) {
// function's body
}

A function is composed of five elements:

  1. A function keyword
  2. The function's name
  3. A list of zero or more parameters
  4. A code block ({...})
  5. The function's body
Buy CSS Flexbox book

Types of JavaScript Functions

The four types of JavaScript functions are:

  • Function declaration
  • Function expression
  • Arrow function expression
  • Immediately invoking function expression

Let's discuss each type.

What Is a JavaScript Function Declaration?

A function declaration is a function created without assigning it to a variable.

note

We sometimes call function declaration a "function definition" or "function statement."

Here's an example:

function addNumbers() {
return 100 + 20;
}

Try it on StackBlitz

The function above is a function declaration because we defined it without storing it in a variable.

What Is a JavaScript Function Expression?

A function expression is a function you create and assign to a variable.

Here's an example:

const myFuncExpr = function addNumbers() {
return 100 + 20;
};

Try it on StackBlitz

The function above is a named function expression that we assigned to the myFuncExpr variable.

You can also write the snippet above as an anonymous function expression like so:

const myFuncExpr = function () {
return 100 + 20;
};

Try it on StackBlitz

The function above is an anonymous function expression that we assigned to the myFuncExpr variable.

note
  • An anonymous function is a function with no name.
  • A named function is a function with a name.

A named function's main advantage is that the name makes it easier to trace an error's origin.

In other words, suppose your function threw an error. In such a case, if the function is named, a debugger's stack trace will contain the function's name. Therefore, you will find it easier to identify the error's origin.

What Is a JavaScript Arrow Function Expression?

An arrow function expression is a shorthand way to write a function expression.

Syntax of an arrow function

We define an arrow function with the equality and the greater-than symbols (=>). Here is the syntax:

const variableName = () => {
// function's body
};

Example of an arrow function

const myFuncExpr = () => {
return 100 + 20;
};

Try it on StackBlitz

You can see that we defined the function without a function keyword and a function name.

You have to omit the function keyword and function name while writing an arrow function expression. Otherwise, JavaScript will throw a SyntaxError.

Important stuff to know about the JavaScript arrow function expression

Here are three essential facts to remember when using an arrow function expression.

1. The parameters' parentheses are optional

Suppose your arrow function contains only a single parameter. In such a case, you can omit its parentheses.

const myFuncExpr = a => {
return a + 20;
};

Try it on CodePen

2. The curly brackets and return keyword are optional

Suppose your arrow function contains only a single statement. In that case, you can omit its curly brackets and return keyword.

const myFuncExpr = (x, y) => x + y;

Try it on StackBlitz

In the snippet above, we implicitly returned the sum of parameters x and y by removing the curly brackets and the return keyword.

info

Whenever you choose to omit the curly brackets, also make sure that you remove the return keyword. Otherwise, the computer will throw a SyntaxError.

3. Use parentheses to wrap any implicit object return

Suppose you wish to return an object implicitly. In such a case, wrap the object in a grouping operator (...).

For instance, consider the code below:

const myFuncExpr = () => {
carColor: "White",
shoeColor: "Yellow",
};

Try it on CodeSandbox

The snippet above will throw a SyntaxError because JavaScript assumed the curly brackets to be the function body's code block—not an object literal.

Therefore, whenever you wish to return an object literal implicitly—without using the return keyword explicitly—make sure to encase the object literal in a grouping operator.

Here's an example:

const myFuncExpr = () => ({
carColor: "White",
shoeColor: "Yellow",
});

Try it on CodeSandbox

Note that you can use the grouping operator to return any single value. For instance, the snippet below grouped the sum of x and 56.

const myFuncExpr = x => (x + 56);

Try it on CodePen

Let's now discuss the fourth type of JavaScript function.

What Is a JavaScript Immediately Invoked Function Expression?

An immediately invoked function expression (IIFE) is a function expression that invokes itself automatically.

note

We sometimes call an IIFE a "Self-Invoking Function Expression" or "Self-Executing Anonymous Function Expression."

Syntax of an IIFE

(function () {
/* ... */
})();

An IIFE is composed of three main components:

  1. A grouping operator: The first pair of parentheses ()
  2. A function: Enclosed within the grouping operator
  3. An invocator: The last pair of parentheses ()

Examples

Below are examples of an IIFE.

How to define a named IIFE

(function addNumbers() {
console.log(100 + 20);
})();

Try it on StackBlitz

The function in the snippet above is a named self-invoking function expression.

How to define an anonymous IIFE

(function () {
console.log(100 + 20);
})();

Try it on StackBlitz

The function in the snippet above is an anonymous self-invoking function expression.

How to define an arrow function IIFE

(() => console.log(100 + 20))();

Try it on StackBlitz

The function in the snippet above is an arrow self-invoking function expression.

How to define an async IIFE

(async () => console.log(await (100 + 20)))();

Try it on StackBlitz

The function in the snippet above is an asynchronous self-invoking function expression.

So, now that we know what an Immediately Invoked Function Expression is, we can discuss how it works.

How does an IIFE work?

By default, the computer does not know what data type your code is until it evaluates it.

For instance, suppose you ask the computer to process 4. In such a case, the system won't know if 4 is a number type until it evaluates it.

Therefore, JavaScript will throw a SyntaxError if you use any number method directly on 4.

Here's an example:

// Convert 4 to a string value:
4.toString();

// The invocation above will return:
"Uncaught SyntaxError: Invalid or unexpected token"

Try it on CodeSandbox

The computer threw a SyntaxError because it does not recognize 4 as a number data type.

Buy CSS Flexbox book

However, suppose you assign 4 to a variable. In that case, the computer will first convert it to a number data type before storing it into the variable.

Afterward, JavaScript will allow you to use any number methods on the number variable.

Here's an example:

// Assign 4 to a variable:
const myNum = 4;

// Convert myNum's content to a string value:
myNum.toString();

// The invocation above will return: "4"

Try it on CodeSandbox

The snippet above did not return any error because JavaScript evaluated myNum as a number data type.

But you don't have to assign 4 to a variable before the computer can evaluate its data type appropriately.

You can alternatively put your value in parentheses to force the computer to evaluate its data type before using it for other things.

For instance, consider this snippet:

// Evaluate 4's data type and turn it into a string value:
(4).toString();

// The invocation above will return: "4"

Try it on CodeSandbox

The snippet above enclosed 4 in parentheses to make the computer evaluate its data type before using the toString() method to convert it to a string value.

Using parentheses to make JavaScript evaluate your code's data type first is what happens in an Immediately Invoking Function Expression (IIFE).

For instance, consider this example:

// Evaluate the function's data type and immediately invoke it:
(function addNumbers() {
console.log(100 + 20);
})();

// The invocation above will return: 120

Try it on StackBlitz

The snippet above enclosed the addNumbers function in parentheses to make the computer evaluate its data type before invoking it immediately after the evaluation.

Overview

In this article, we discussed what a JavaScript function object is. We also used examples to see how it works.

Everything you need to sell courses, webinars, downloads, and community.