The A-Z of JavaScript Functions

Emma Lowe
3 min readSep 22, 2020

--

Contents:

  1. Declarative vs Expressive Functions
  2. Function Hoisting
  3. Anonymous Functions
  4. Arrow Functions
  5. Pure Functions
  6. IIFE — Immediately Invoked Function Expression

1. Function Declaration vs Expression

In JavaScript a function is just a value. This means that we can create functions that are named or unnamed. Named functions are function declarations. Unnamed functions are function expressions and look like this:

Example of function expression

All we are doing here is taking a function (a value) and setting it equal to some variable. Because the function itself does not have a name it is called an anonymous function. We can call the variable “addTwo” to use the function.

A function declaration looks like this:

Example of function declaration

2. Function Hoisting

Have you ever made a function call and then later in the code declared the function and wondered why it worked? This is called function hoisting. It looks like this:

Example of function hoisting

Function declarations are hoisted to the top of their scope while function expressions are not.

3. Anonymous Functions

To put it simply, anonymous functions are unnamed functions. The advantage to using anonymous functions is it helps to simplify your code. The disadvantage is that if there is an error in the call stack the error message will not contain a function name and be harder to debug.

We can use anonymous functions as arguments for other functions. Like so:

Example of an anonymous function being used as parameter for another function

If you want a function to be immediately invoked (run) after its declaration we can create an anonymous function like this:

Example of an immediately invoked anonymous function

Arrow functions are also anonymous functions. More on that in #4.

4. Arrow Functions

Since the release of ES6, arrow functions have been around. A shorter syntax for creating an anonymous function, arrow functions are useful to simplify and shorten code.

Lets take this function:

Anonymous function example

With arrow syntax it turns into this:

Arrow function example

5. Pure Functions

Pure functions don’t change or rely on code outside of the function. A pure function takes in parameters and returns a value. In other words, it has no side effects. If parameters of equal value are passed to a pure function, it will always return the same output.

Example of pure function

Functions that have side effects or rely on outside code are called impure functions.

6. IIFE — Immediately Invoked Function Expression

An IIFE is a function that is invoked as soon as it is declared. We do this by appending parenthesis ( ) at the end of a function declaration.

IIFE example

--

--

Emma Lowe

Emma is a software dev who synthesizes information best through writing. She believes clear documentation and communication go hand in hand with good code.