Four Ways to Create a Function in JavaScript

There are four ways a function can be created in JavaScript. They are as follows:

  • A function as a statement
  • A function as an expression
  • A function as an arrow function
  • A function created using the Function constructor

All four ways of function creation have distinct features such as an arrow function that does not have its own this object, a function statement that is hoisted on the top of the execution context, and a function expression that can be immediately invoked without creating a separate scope. Having a good understanding of various characteristics of different types of JavaScript functions is useful to write better code. This article explains these functions

A Function as a Statement

A function as a statement can be created as shown the following code example:

function Add(num1, num2) {
    let sum = num1 + num2;
    return sum;
}
 
let res = Add(78);
console.log(res); // 15

A function statement starts with the function keyword. It can return a primitive type value, object, or another function. For example, a function statement can return an object as shown in the following code example:

function getProduct() {
    let product = {
        Id: 1,
        Title: 'Book',
        Price: 30
    };
    return product;
}
 
let p1 = getProduct();
console.log(p1); // prints product object 

The main characteristic of a function statement is it is hoisted at the top of the execution context. Therefore, you can call a function statement before it is declared, as shown in the following code example:

Liked so far ? Read full article on the Telerik Blog

https://www.telerik.com/blogs/four-ways-to-create-a-function-in-javascript

Thanks for reading.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading