Different ways to Create functions in Javascript
Today, we will learn different ways to create functions in Javascript.
Before starting, a reminder about what is a function:
A Function is a block of statements that is designed to perform a particular task.
function test(){ console.log("Hi from Function");
}
test()
There are four ways a function can be defined in JavaScript. They are as follows:
- Function Declaration
- Function Expression
- Arrow Function
- Using Function Constructor
Let's have a look at them one by one.
Function Declaration
A function declaration starts with the function keyword. It can accept any parameters and return anything as per the use case.
function Multiply(num1,num2){ return num1* num2; ;
} let result= Multiply(10,5);
console.log(result);
The main characteristic of a function declaration is that this function will get hoisted on the top of the execution context. It means that you can call this function even before it is declared.
let result= Multiply(10,5);
console.log(result); function Multiply(num1,num2){ return num1* num2; ;
}
As you can see, that Multiply function is called before it is created.
Function Expression
In a function expression, you assign a function reference to a variable.
let test = function(){ console.log("Hi from Function");
}
test()
The main difference between function declaration and function expression is that function defined with function declaration approach get hoisted but function defined with function expression doesn't get hoisted.
let result= Multiply(10,5);
console.log(result); let Multiply = function(num1,num2){ return num1* num2; ;
}
As you can see, we got the ReferenceError when we tried calling the Multiply function because it is not hoisted on top of the execution context.
Arrow Function
The arrow functions are a newly added feature in ECMA 2015. We can say an arrow function expression is a compact alternative to a traditional function expression
let test = function(){ console.log("Hi from Function");
} let Multiply = (num1,num2) => { return num1* num2; }
let result= Multiply(10,5);
Arrow function can be written in more one than form based on use case.
var add = (num1, num2)=> num1+num2; let greet = ()=>console.log('hey'); var test = (name,age)=>{ if(age > 20){ return 'age is more than 20'; } return 'age is less than 20';
}
Function Constructor
By using the function constructor also, we can creates a new Function object
const multiply = new Function('a', 'b', 'return a * b'); console.log(multiply (10,5));
This approach of creating the function suffers from security and performance issues. That's why it is not advisable to use this approach.
In this post, you learned about various ways of creating a function.
I hope you found the article useful. Thanks for reading.
nice