8 ways to define a function in JavaScript

Overview

Functions are one of the most important aspects of programming. A function is an object which takes inputs as arguments and calculates a value with some statements. Here In this guide, we’ll talk about the number of ways to define a function in JavaScript

1. Function declaration

A function declaration is the most common and traditional way to define a function In JavaScript. Let’s take a look at the syntax.

function welcome(name){
    alert(`Welcome ${name}`)
}
welcome("John") //Welcome John

Here, the name is the variable that passed as a parameter to the function. And “John” is the actual data that passed as an argument to the function parameter.

JavaScript function declarations are hoisted. That means we can call the function before even declaring it. Consider the below example.

getUserData("John",30)
//User is John and ages is 30.

function getUserData(name,age){
       return `User is ${name} and age is ${age}
}

2. Function expressions

A JavaScript function can also be defined as an expression. Apart from function declaration here we store the function inside a variable.

let sum = function(num1,num2){
                return num1+num2;
}
sum(2,3) //5

We can invoke the function with the help of the variable name. But here we can’t call the function before declaring it. Only declarative functions are hoisted.

3. Generator function

Usually, when a function gets called It executes the logic line by line. We can’t stop a function until you return or throw an error during the execution.

A generator function can be stopped in the middle way of the execution. And later we can call the function again, and this time the function will execute the code from where It’s stopped.

A generator function can be declared with a keyword function followed by an asterisk ( * ).

Let’s take an example,

function * getUserData(name,age,email){
       console.log(`Name of the user ${name}`)
       yield 'pause'
       console.log(`Age of user ${age}`)
       yield 'pause'
       console.log(`Email of the user ${email}`)
       yield 'End'
}

Note: A generator function returns an object when the function gets called. Which later we can use to call the function again. We use the yield keyword to stop the function to execute while running.

Example of an object returned from a generator function.

{
 value:Any,
 done: true | false
}

Here value means the actual value returned from the generator function and the done defines whether function completed execution or not.

Let’s call the generator function. Initially we store the function inside a variable.

const userData = getUserData("john",30,"johndoe@mail.com")
userData.next().value 
//Name of the user John

userData.next().value
//Age of the user 30

userData.next().value 
//Email of the user "johndoe@gmail.com"

4. Arrow function

Arrow functions were Introduced in ES6 aka ECMA2015. These are shorter syntactic functions compared to traditional function declarations. Let’s take an example,

let sum = (num1,num2) => {
      return num1+num2;
}
sum(3,4) //7

And if the function has only one parameter and does not have more than one statements, we can re-write the function as,

let name = name => `Welcome ${name}`;

As you can see we have omitted the parameter parenthesis and the return keyword from the function.

Arrow functions have a great advantage over traditional functions. Arrow functions do support Lexical binding. This means It automatically takes this keyword from the surroundings. Let’s understand this with an example.

//consider a function declaration
function User(name,age){
      this.name = name;
      this.age = age;
      this.info = function(){
         setTimeout(function(){
            console.log(`User is ${this.name} and age is ${this.age})
      },2000)
}
let user1 = new User("John",30)
user1.info() //User is undefined and age is undefined

The reason behind we got undefined is due to the scope of this keyword inside the function which gets called as the callback for setTimeout function.

That means function declaration can’t take this context from parent functions. To solve this we can use arrow functions.

The above function can be rewritten as follows,

//declaring the function
function User(name,age){
      this.name = name;
      this.age = age;
      this.info = function(){
         setTimeout(() => {
            console.log(`User is ${this.name} and age is ${this.age})
      },2000)
}
let user1 = new User("John",30)
user1.info() //User is John and age is 30.

As you can see arrow functions are one of the best ways to define a function in JavaScript. You can read more about arrow functions here. Arrow function expressions by Mozilla.

5. Async functions

ways to define a javascript function

JavaScript is a synchronous language. This simply means JavaScript engines run the codes line by line without having to wait for something to complete. There are multiple scenarios we need to execute something parallel or one after another. There we have to use async functions.

Async/await functions are addons to the Promises in JavaScript. If you don’t know what is Promises make sure you check out that first. Promises in JavaScript.

An async function always returns a promise. Other values from the return are wrapped inside the resolved object. Let’s understand It in detail,

async function number(){
   return 1;
}
number().then(alert) //outputs 1

That means the function returns a promise object which we can use the execute the function In an asynchronous way. Cool Isn’t it? Wait there is more.

An await keyword can only be used inside an async function. Await helps a JavaScript code to wait for a promise to settle and return its output.

Consider the below example,

async function names(){
 let promise = new Promise(resolve,reject) => {
      setTimeout(() => {
        resolve('Done'),1000)
});
let result = await promise;
alert(result)
}

names() // Alerts 'Done' After promise resolved.

Here the result variable waits for promise variable to complete It’s execution and binds the resolved result to result variable.

6. Exported functions

The export statement is used when we need to use a particular function or objects from a module or a piece of program to use it in other modules with an import statement.

Export and import statements are much useful in NodeJS projects such as React, Express etc. Let’s see how It’s done.

//Consider a module Expenses.js
let sum = function(num1,num2){
    return num1+num2;
}
const names = ["john","Doe","Albert","Mary"]
const fruit = {
        name:"Apple",
        color:"Red",
     }
export {sum,names,fruit}

And later in another module we can import it using import statement.

//consider another module Balance.js
import {sum,names,fruit} from './Expenses.js'
sum(2,4) //6

Note: We have used { } to export multiple objects from a module. We can omit the curly braces when we need to export only a single object. And in this case, we’ll export the object using the default keyword.

/ModuleA
const sum = function(num1,num2){
    return num1+num2;
}
export default sum;

//Import in ModuleB
import sum from 'ModuleA';

7. Object property function

Objects in JavaScript, just as in other programming languages can have attributes, values, and methods. Objects can be compared to real-time objects. We can declare a function inside an object which is called object property functions.

Consider the following object of a car.

const FerrariGTB = {
     version:"Spider",
     fuelType:"Petrol",
     Tranmission:"Automatic",
     cost:"32M",
    showDetails() {
        console.log(`Ferrari version is ${this.version}, fuel type is ${this.fuelType} and cost is ${this.cost}`);
    }
};
FerrariGTB.showDetails()
//Ferrari version is Spider, fuel type is Petrol and cost is 32M

8. Class functions

A JavaScript class is a type of function, but instead of using a function keyword to declare one, we use the class keyword to declare class functions. And we’ll assign the properties inside a constructor just like any other object-oriented language.

Let’s have a look at how we can define a class function and methods.

class User{
   constructor(name,age){
       this.name = name;
       this.age = age;
   }
   userInfo(){
     return `User is ${this.name} And age is ${this.age}`;
 }
}

And we can create a new object with the help of above class and the attributes.

let user1 = new User("John",30)
user1.userInfo()
//User is John And age is 30.

Conclusion

These are some of the ways you can define a function In JavaScript. There are other methods like getter, setter functions, Object dynamic property functions also available to use.

Anyway, I hope this guide helped you to understand the ways you can define a function in JavaScript. If so, feel free to share with fellow programmers and comment your opinions below. Thanks for reading, have a good day!

Leave a Comment

Your email address will not be published. Required fields are marked *