Introduction
In this article, we will cover Types of functions in JavaScript. Before we start, Let's understand the objective of this demonstration, which tells what exactly will be covered in this article.
- Named Functions
- Anonymous Functions
- Arrow Functions
- IIFE (Immediately Invoked Function Expression)
- Higher-Order Functions
- Constructor Functions
So, Let's get started.
Named Functions
These are regular functions that are defined with a name and can be called by that name.
function displayName(name) {
console.log(`Hello, ${name}!`);
}
displayName("Vishal");
// Output: Hello, Vishal"));
Anonymous Functions
These are functions that do not have a name and are often used as arguments to other functions or assigned to variables.
const sum = function(a, b) {
return a + b;
}
console.log(sum(3, 5));
// Output: 8
Arrow Function
Introduced in ECMAScript 6 (ES6), arrow functions provide a concise syntax for writing functions, especially when you want to use a simple one-liner.
const multiply = (x, y) => x * y;
console.log(multiply(4, 6));
// Output: 24
IIFE (Immediately Invoked Function Expression)
These are self-invoking functions that execute as soon as they are defined.
(function (x, y, z) {
console.log(x);
console.log(y);
console.log(z);
})(100, 200, 300);
// Output: 100
// Output: 200
// Output: 300
Higher-Order Functions
Functions that can accept other functions as arguments and/or return functions.
Eg: map(), filter(), reduce()
let arr = [5,10,15,20,25];
let newarr = arr.map((element)=> {
return element + 5;
})
console.log(newarr);
// Output: [10,15,20,25,30]
Constructor Function
Functions used to create instances of objects are often used for defining classes and creating objects with shared properties and methods
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = new Person("Vishal", 33);
console.log(person.name);
console.log(person.age);
// Output: Vishal
// Output: 33
Summary
In this article, I have tried to cover Types of functions in Javascript.