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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s