A function is a reusable piece of code that runs when you invoke it. Functions allow you to reuse code, making it more modular and easier to maintain.

There are several ways to create functions in JavaScript. Here you will learn the different ways to create functions and how to use them.

Function Declarations: The Straightforward Way

One way you can create functions in JavaScript is through function declarations. A function declaration is a function in JavaScript that follows the syntax below.

        function functionName(parameters) {
  // code goes here...
  return "This is a function declaration";
}

The components of the code block above include:

  • The function keyword: This keyword declares a function.
  • functionName: This is the name of the function. In practice, it should be as descriptive and meaningful as possible, indicating what the function does.
  • parameters: This represents the function parameters. Parameters are an optional list of variables that you can pass to a function when you call it.
  • The function body: This contains the code that the function will run when you call it. It's surrounded by curly braces {} and can contain any valid JavaScript code.
  • The return statement: This statement stops a function’s execution and returns the specified value. In the case above, calling the function would return the string “This is a function declaration”.

For example, the function declaration below takes three numbers as parameters and returns their sum.

        function addThreeNumbers(a, b, c) {
  return a + b + c;
}

To call a function declaration in JavaScript, write the function name followed by a set of parentheses (). If the function takes any parameters, pass them as arguments within the parentheses.

For example:

        addThreeNumbers(1, 2, 3)  // 6

The code block above calls the addThreeNumber functions and passes 1, 2, and 3 as arguments to the function. If you run this code, it will return the value 6.

JavaScript hoists function declarations, meaning you can call them before you define them.

For example:

        isHoisted();  // Function is hoisted

function isHoisted() {
  console.log("Function is hoisted");
  return true;
}

As shown in the code block above, calling isHoisted before defining it would not throw an error.

Function Expressions: Functions as Values

In JavaScript, you can define a function as an expression. You can then assign the function value to a variable or use it as an argument to another function.

They are also known as anonymous functions since they have no names, and you can only call them from the variable you assigned them to.

Below is the syntax for a function expression:

        const functionName = function () {
  return "Function expression";
};

To call a function expression in JavaScript, write the variable name you assigned to the function followed by a set of parentheses (). If the function takes any parameters, pass them as arguments within the parentheses.

For example:

        functionName();  // Function expression

Function expressions are handy when creating functions that run in other functions. Typical examples include event handlers and their callbacks.

For example:

        button.addEventListener("click", function (event) {
  console.log("You clicked a button!");
});

The example above used a function expression that takes an event argument as a callback to the addEventListener function. You don't have to call the function explicitly when you use a function expression as a callback. It automatically gets called by its parent function.

In the case above, when the event listener receives a click event, it calls the callback function and passes the event object as an argument.

Unlike function declarations, function expressions are not hoisted, so you can’t call them before you define them. Trying to access a function expression before you define it will result in a ReferenceError.

For example:

        isHoisted();  // ReferenceError: Cannot access 'isHoisted' before initialization

const isHoisted = function () {
  console.log("Function is hoisted");
};

Arrow Functions: Compact and Limited

ES6 introduced a shorthand for writing anonymous functions in JavaScript called arrow functions. They have a concise syntax that can make your code more readable, especially when dealing with short, single-line functions.

Unlike other methods of creating functions, arrow functions don't require the function keyword. An arrow function expression consists of three parts:

  • A pair of parentheses (()) containing the parameters. You can omit the parentheses if the function only has one parameter.
  • An arrow (=>), which consists of an equal sign (=) and a greater than sign (>).
  • A pair of curly braces containing the function body. You can omit the curly braces if the function consists of a single expression.

For example:

        // Single parameter, implicit return
const functionName = parameter => console.log("Single parameter arrow function")

// Multiple parameters, explicit return
const functionName = (parameter_1, parameter_2) => {
  return "Multiple parameter arrow function"
};

When you omit the curly braces, the arrow function implicitly returns the single expression, so there’s no need for the return keyword. On the other hand, if you don't omit the curly braces, you have to explicitly return a value using the return keyword.

Arrow functions also have a different this binding compared to regular functions. In regular functions, the value of this depends on how you call the function. In an arrow function, this is always bound to the this value of the surrounding scope.

For example:

        const foo = {
  name: "Dave",
  greet: function () {
    setTimeout(() => {
      console.log(`Hello, my name is ${this.name}`);
    }, 1000);
  },
};

foo.greet(); // Logs "Hello, my name is Dave" after 1 second

In the example above, the arrow function inside the greet method has access to this.name, even though the setTimeout function calls it. A normal function would have its this bound to the global object.

Immediately Invoked Function Expressions (IIFEs)

As the name implies, an immediately invoked function (IIFE) is a function that runs as soon as its defined.

Here’s the structure of an IIFE:

        (function () {
  // code here
})();

(() => {
  // code here
})();

(function (param_1, param_2) {
  console.log(param_1 * param_2);
})(2, 3);

An IIFE consists of a function expression wrapped inside a pair of parentheses. Follow it with a pair of parentheses outside the enclosure to invoke the function.

You can use IIFEs to create scopes, hide implementation details, and share data between multiple scripts. They were once used as a module system in JavaScript.

Creating a Function in Many Different Ways

Understanding how to create functions in JavaScript is crucial. This is true for a basic function that carries out a simple computation or a sophisticated function that interacts with other parts of your code.

You can use the techniques discussed above to build functions in JavaScript and structure and organize your code. Select the approach that best suits your demands, as each has various benefits and applications.