JavaScript – Types of Functions

CodingTute

JavaScript

In this tutorial you will learn the types of functions supported by JavaScript and its usage.

Function declarations

These are functions that are declared using the function keyword followed by the function name, a list of parameters in parentheses, and a function body. Function declarations are hoisted, which means that they can be called before they are defined in the code. For example:

function add(x, y) {
  return x + y;
}

Function expressions

These are functions that are assigned to a variable. There are two types of function expressions: anonymous function expressions and named function expressions.

Anonymous function expressions are functions that don’t have a name, while named function expressions have a name that can be used within the function itself. Function expressions are not hoisted. For example:

// anonymous function expression
const add = function(x, y) {
  return x + y;
};

// named function expression
const add = function namedAdd(x, y) {
  return x + y;
};

Arrow functions

These are a concise way of writing function expressions in JavaScript. They use the => syntax and do not have their own this, arguments, or super binding. Arrow functions are not hoisted. For example:

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

Method functions

These are functions that are associated with an object and can be accessed using the . operator. For example:

let person = {
  name: "John",
  greet: function(name) {
    console.log("Hello, " + name);
  }
}
person.greet("Bob");

Constructor functions

These are functions that are used to create objects using the new keyword. Constructor functions are usually named with an initial capital letter to distinguish them from other functions. For example:

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

const person = new Person('John');

Generator functions

These are functions that can be paused and resumed using the yield keyword and are denoted by the * symbol after the function keyword. For example:

function* infiniteSequence() {
  let i = 0;
  while (true) {
    yield i++;
  }
}

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.