A function is piece of code or group of statements that performs a particular task. The code within a function gets executed only when it is referenced or called. For example, we can write a function to add two numbers.
In JavaScript (JS), there are many different ways to do things. In this article I will discuss multiple ways to define a function in JS.
1. Function Declaration:
Function declarations are probably the most familiar and traditional way of defining a function in JavaScript land. We type the function keyword followed by a name for the function, followed by opening and closing parentheses, followed by opening and closing curly brackets.
Example:
function greet(){
console.log('Welcome to Datatype!');
}
// Execute or call the function
greet(); // Welcome to Datatype!
This creates a named function greet which is accessible in the current scope. It is not necessary to maintain the order i.e. a function can be called before it is written in the code. It won’t matter, because the function gets hoisted to the top of its container scope. For example, following code will execute without any error.
greet(); // Welcome to Datatype!
function greet(){
console.log('Welcome to Datatype!');
}
The function name can be anything of your choice, but there are few rules you should follow while naming function. You can read Javascript Naming-Conventions to know more.
2. Function Expression:
In this approach we define an anonymous function and assigned it to a variable for reference.
var greet = function(){
console.log('Welcome to Datatype!');
}
greet(); // Welcome to Datatype!
Note: In this approach only function declaration is hoisted, not the entire function. So, if we call greet() function before the function is written, it will throw undefined error.
greet(); // Error: greet is undefined
var greet = function(){
console.log('Welcome to Datatype!');
}
3. Named Function Expression:
It is similar to Function Expression except instead of assigning the variable to an anonymous function, we’re assigning it to a named function with the name welcome. Note that here function name (welcome) is accessible inside the function block only.
var greet = function welcome(){
console.log('Welcome to Datatype!');
}
greet(); // Welcome to Datatype!
welcome() // ReferenceError: welcome is not defined
4. Immediately Invoked Function Expression (IIFE) :
IIFE is an anonymous function which gets executed as soon as in has been declared.
// Syntax:
(function () {
statements
})();
//Example:
var greet= (function () {
var message= "Hello there!";
return message;
})();
// Immediately creates the output:
"Hello there"
To learn more checkout this article : What is IIFE in Javascript?
5. Function Constructor:
This method is extremely old and it is not used much now-a-days. In this approach we pass several arguments first and then define the function body.
var greet = new Function('arg1', 'arg2', 'console.log(arg1 + ", " + arg2)');
greet('Hello', 'there!'); // 'Hello, there!'
It is equivalent to JS eval() method, so due to security reasons Function Constructors are not recommended.
6. Arrow Function:
Arrow Function is a new feature which was included in ES6 (JavaScript 2015) release. It is similar to regular Function Expression with some syntactical changes so that we can have same output by writing less code.
var greet = () => {
return "Welcome to Datatype!";
}
Arrow Functions return value by default. So, if the function has only one statement, the syntax becomes much more shorter!
var greet = () => "Welcome to Datatype!";
greet(); // Welcome to Datatype!
// With argument:
var greet = (user) => "Hello " + user;
greet('Guest') // Hello Guest
Note: Handling this is different in Arrow Function, in fact the this context is not preserved in Arrow Function (there is no binding of this). So, choice of using regular function or arrow function depends on what you are trying to achieve. If this context is not required use arrow functions, else use regular functions