A function is a subprogram designed to perform a particular task. Functions are executed when they are called. This is known as invoking a function. Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined. Functions are objects. A function can have multiple or no parameters at all.

Different type of functions in JavaScript

1. Function declaration | Basic Syntax

// function declaration
function isEven(num) {
return num % 2 === 0;
}

2. Function Expression

var fullName = function(firstName, lastName) {
return `${firstName} ${lastName}`;
}
fullName("Abhay", "Jain"); // Abhay Jain

3. Arrow Function

First:

const double = (value) => {
return value * 2
}
double(10); // 20

Second:

const double2 = value => value * 2;
double2(10); // 20

Third:

const noise = () => console.log("Pling");
noise(); // Pling

or

const noise2 = _ => console.log("Pling");
noise2(); // Pling

Fourth:

const addAll = (x, y, z) => x + y + z;addAll(10, 20, 30); // 60

Fifth:

const multiply = (a = 2, b = 3, c = 1) => a * b * c;
multiply(2, 2, 2); // 8
multiply(2, 2); // 4
multiply(3); // 9
multiply(); // 6

Function Shorthand methods:

const fruits = {  
items: [],
add(...items) {
this.items.push(...items);
},
get(index) {
return this.items[index];
}
};
fruits.add('mango', 'banana', 'guava');
fruits.get(1); // banana

add() and get() methods in fruits object are defined using short method definition. These methods are called as usual: fruits.add(...) and fruits.get(...).

4. Generator Function:

function * generatorFunction() { 
yield 'Hello, ';
console.log('I will be printed after the pause');
yield 'World!';
}
const generatorObject = generatorFunction();
console.log(generatorObject.next().value);
console.log(generatorObject.next().value);
console.log(generatorObject.next().value);
// output should be following below.
// Hello,
// I will be printed after the pause
// World!
// undefined

Function with: new Function

var sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6)); // 8

Developer with 3 yrs of industrial experience in developing scalable web applications.