Defining Functions in JavaScript

Defining Functions in JavaScript

As JavaScript developers we all might have worked with functions and we might have used the function keyword to define our functions. I started learning and understanding JavaScript initially by looking into the code used in my project without any formal training of the language. That is when I got to see the ways in which we define functions but Would'nt that be great if we know these language features ahead of time ?

In this post let us try to understand the different ways of defining a function in JavaScript and the differences between them.🙂

There are 4 different ways in which we can define a JavaScript function.

  1. Function Declaration
  2. Function Expression
  3. Arrow Functions
  4. Nested Functions

Function Declaration

This is the most common way of defining functions. We use the function keyword followed by a function name,parameters,code block that defines our function along with the return statement if there is any value to be returned or it returns undefined. This method of defining functions assigns function name as a variable containing the function object. Functions defined using this method of function declaration is hoisted on the top of the script or function or code block in scope. This means that we can define the function anywhere and invoke the function even before the code block defining the function.

A small introduction to Hoisting

The scenario mentioned in the above statement is all possible because of the feature of Hoisting in JavaScript. When the JavaScript engine gets a script for execution for the very first time there is a javascript execution context that gets created. This process has two steps.

  1. Creation Phase
  2. Execution Phase It is the creation phase in which all the variables and functions are moved to the top. The variables are also assigned a value of undefined by default and the values gets changed in the execution phase when the code gets executed line by line.

Example of Function Declaration

//The function is called even before it is defined.
add(4, 5);
//The add() function is defined
function add(x, y) {
  return x + y;
}

If the above code is run in a script file altogether it would give the expected result since the JavaScript engine in the browser takes care of the hoisting the function. However if we try running the add() function in the web browser console before defining the function it would give an error.

Function Declaration

Function Expression

It is another way of defining functions and it more seems like assigning the function to a variable or constant and hence it is called function expression. The keyword function is optional. The function name would be required in the cases of a recursive function where we will have to call the function by the name. If we still provide names in the function expression it would assign the binding of the function to a local variable by that name in the scope. As seen in the function declaration section that the name specified after the function keyword creates a variable by that name and assigns the function object to it. In case of function expression the name is optional and it is upon us to declare that function object to a variable or a constant. You would see that in most of the function expressions we use constant instead of a variable so that we do not overwrite the function by assigning new value to the variable.

//A function expression without a function name that returns the sum of two numbers
//provided as parameters
const sum = function (x, y) { return x + y; };
//A function expression that includes a function name which is useful for recursion
const factorial = function fact(x){ if (x <= 1) return 1; else return x*fact(x-1); };

Immediately Invoked Function Expression

We can also invoke the function immediately at the time of defining the function with a function expression. The code below shows an example of such IIFE.

const sum = function (x, y) { return x + y; }(4,5);

One important difference between a function declaration and a function expression is unlike function declaration the variable to which we have assigned a function expression cannot to used prior to the assignment of the function expression since function expressions are not hoisted by the JavaScript engine the way it is done for function declarations.

Arrow Functions

Arrow functions is a part of ES6 and it is a shorthand way of defining functions as compared to the function declaration and function expression. This type of function definition uses Arrow (=>) to separate the function parameters with the function body. This method of defining function has become very popular due to its compact nature.

The arrow function for returning the sum of two numbers can be expressed as -

const sum = (x, y) => { return x + y; };

The parenthesis () contains the parameters to be passed to the function body. The curly braces {} contains the function body. Since the function body just contains a single statement we can even ignore the return keyword curly braces and the semicolon. The arrow function by default return the single statement in the function body without a return keyword. However we will have to mentioned the return statement explicitly if there are more than one statement in the function body.

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

When there are no parameters to be passed we need to put () before the arrow => however the parenthesis can be ignore if there is only one parameter to the function.

One important difference of defining function with arrow function from other ways is that the arrow function does not have a prototype property and so other classes or function cannot use arrow function to extend themselves.

You can go through my article for prototype to understand prototype and prototype chaining in JavaScript.

Nested Functions

We can also define a JavaScript Function inside another JavaScript Function. The inner function can access the parameters and the variables of the outer function when they are nested.

function sum(x,y){
    //The function add() has access to the parameters x,y of the function sum()
    function add(){
        return x+y;
    }
   return add();
}

Conclusion

There are many ways to define functions in JavaScript and not just the traditional way of defining it by using the function keyword unlike other programming languages. It is very important to understand these language features so that we can use them effectively.

Happy Coding.💻

Book Recommendation

I would recommend you to refer to the book JavaScript - The Definitive Guide by David Flanagan for an in-depth understanding of the JavaScript Language.