DEV Community

Cover image for Demystifying JavaScript Functions: A Guide to Function Types
Mohammad AbdulHakim
Mohammad AbdulHakim

Posted on

Demystifying JavaScript Functions: A Guide to Function Types

In JavaScript, there are several types of functions, including:

1- Function declarations

A function declaration defines a named function using the function keyword and can be called anywhere in the code.

function addNumbers(a, b) {
  return a + b;
}

console.log(addNumbers(2, 3)); // logs 5
Enter fullscreen mode Exit fullscreen mode

2- Function expressions

A function expression defines a function as part of an expression, such as assigning a function to a variable.

var multiplyNumbers = function(a, b) {
  return a * b;
};

console.log(multiplyNumbers(2, 3)); // logs 6
Enter fullscreen mode Exit fullscreen mode

3- Arrow functions

Arrow functions are a shorthand syntax for defining functions using the => arrow operator. They are often used for concise one-line functions.

var divideNumbers = (a, b) => a / b;

console.log(divideNumbers(6, 3)); // logs 2
Enter fullscreen mode Exit fullscreen mode

4- Immediately invoked function expressions (IIFE)

An IIFE is a function that is defined and called immediately. It is often used to create a new scope for variables and avoid polluting the global namespace.

(function() {
  var message = "Hello, world!";
  console.log(message);
})();
Enter fullscreen mode Exit fullscreen mode

5- Methods

Methods are functions that are defined as properties of an object. They can be called using theobject and dot notation.

var calculator = {
  add: function(a, b) {
    return a + b;
  },
  subtract: function(a, b) {
    return a - b;
  }
};

console.log(calculator.add(2, 3)); // logs 5
console.log(calculator.subtract(5, 2)); // logs 3
Enter fullscreen mode Exit fullscreen mode

6- Constructor functions

Constructor functions are used to create new objects of a specific type, often referred to as classes. They use the this keyword to set properties of the new object and are called using the new keyword.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

var alice = new Person("Alice", 25);
console.log(alice.name); // logs "Alice"
console.log(alice.age); // logs 25
Enter fullscreen mode Exit fullscreen mode

7-Callback functions

Callback functions are functions that are passed as arguments to another function and called when the other function completes. They are often used for asynchronous programming, such as handling events or making API calls.

function getData(callback) {
  // make API call and return data
  var data = {name: "Alice", age: 25};
  callback(data);
}

function displayData(data) {
  console.log(data.name + " is " + data.age + " years old.");
}

getData(displayData);These are some of the common types of functions in JavaScript, and each has its own use case and advantages.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)