When building software, reusable codes can be a great help for developers. One way to achieve this is through functions. Functions execute blocks of code on demand. JS has two primary functions: normal functions and arrow functions. This article will show the differences between the two and discuss their uses.
This article will go through the difference between the arrow and normal functions. We will also discuss their real-world applications.
What is a Function?
Functions are one of the building blocks of JavaScript. A function in JavaScript is just like a procedure—a set of statements that perform a task or calculate a value. Still, to qualify as a function, a procedure should take certain inputs and return some output where there is some apparent relationship between the input and output. If you want to use a function, you have to define it somewhere in the scope from which you want to call it.
What is Normal Function?
To create a normal function, we use the "function" keyword followed by an assigned name. Then we create an area where user input will determine outcomes. And the output will be based on sets of instructions provided within brackets.
As we can see, this is an example of normal function. And this function accepts two values and prints their sum:
//an addition function written in javascript
function addition(x, y) {
return x + y;
}
We can call this function by its name:
let answer = addition(9, 18);
console.log(answer); // Output: 27
What is Arrow Function?
Arrow functionsuse the "fat arrow" syntax (=>). Arrow functions offer a more concise way of constructing functions. Arrow functions were introduced with ES6, and they provide a simpler way of writing functions.
The arrow function expression is an alternative to the normal function. With some differences and limitations in usage:
Arrow functions don't have their bindings to arguments, this, or super, and we cannot use them as methods.
Arrow functions cannot be used as constructors. Calling them with new throws a TypeError. They also don't have access to the new.target keyword.
Arrow functions cannot use yield within their body and cannot be created as generator functions.
The below function is similar to the previous function, written as an arrow function:
const addition = (x, y) => x + y; //written in javascript.
A key aspect of arrow functions is their concise and streamlined syntax. With parentheses containing the arguments, a fat arrow (=>), then a function body, it's easy to see how simple they can be. For this example, the function body contains just one expression returning a sum of two parameters. As a result, both curly braces and the return keyword will not be needed.
To call this function, you would use the same syntax as before:
let answer = addition(9, 18);
console.log(answer); // Output: 27
Having examined the syntax of both function types, We will now dive into the divergences between them.
Differences Between Normal Function and Arrow Function
Aspect
Arrow functions
Normal functions
Anonymous
Yes
No
Syntax
Shorter
Longer
Handling multiple expressions
Difficult
Better
"this" keyword behavior
Inherits from a broader scope.
Refers to the object it belongs to ("this").
Constructor functionality
Not suitable for use as a constructor.
Suitable for use as a constructor.
Arguments object
Does not have an arguments object
Has an arguments object
Duplicate named parameters
Not allowed
Allowed
Call, apply, and bind
Do not change the value of this
Can change the value of this
Lexical scoping
Lexically scoped
Functionally scoped
To learn about these differences in detail, read the following.
Arrow functions are anonymous:
Arrow functions are unnamed. It means that they do not have a name and cannot have designated identifiers. Instead, they can be linked with variables or transferred as an argument for another function.
The arrow function can also be assigned to a variable via the code given below:
const addition = (x, y) => x + y; //written in javascript
In the above example, the variable name (addition) is used to refer to the function.
Arrow functions have a shorter syntax:
Arrow functions have a shorter syntax. Making them useful in writing one-line blocks of code. Normal functions are better at handling logic that requires multiple expressions.
E.g., of the normal function that calculates the factorial of a number:
//written in javascript
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
A function that uses recursion for calculating the factorial of a number is what we need. The function should have curly braces and the return keyword, as it contains multiple statements.
Here is the same function written as an arrow function:
//written in javascript
const factorial = (n) => {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
As this function contains various statements. And it cannot be represented as a single expression. The arrow function syntax seems difficult and lengthy.
Absence of "this" value in the Arrow function:
In the case of the arrow function, they do not have their own "this" value. Traditional methods refer to objects they belong to as "this," while arrow methods inherit their context from a broader scope. This can cause issues when using arrow functions with objects.
For example,
//written in javascript
const human = {
name: 'Sourabh',
age: 21,
sayName: function() {
console.log(this. name);
}
};
With our current example, there exists an item referred to as "human".And this has properties such as a given name and age. Alongside these, a function titled "sayName" exists for this individual. It shall be produced on the console whenever it calls its name using the "this" method.
Below is the sayName method written with an arrow function:
//written in javascript
const human = {
name: 'Sourabh',
age: 21,
sayName: () => {
console.log(this. name);
}
};
If we call the sayName function at present, then it would show "undefined" as a result on the console. This occurs because the "this" keyword doesn't indicate the person's object. Rather it points to the global object process (which is none other than a window object. Particularly in web browsers).
Arrow functions cannot be used as constructors:
Not being able to work as the constructor is the main difference between the arrow and regular functions. As we know, Constructors create new object instances uniquely.
For example:
//written in javascript
function Human(name, age) {
this.name = name;
this.age = age;
}
const sourabh = new Person('Sourabh', 21);
console.log(sourabh.name); // Output: Sourabh
In this example, a functional object known as a Person is used to assign two distinct parameters. And these will be used in the formation of an item. The name and age specifications are set for the new creation by the Person function used. A fresh article named sourabh is produced by using a similar format that is used for generating a new instance of an item. Finally, his name will be displayed on the console.
Below we have written the Person function as an arrow function:
//written in javascript
const Person = (name, age) => {
this.name = name;
this.age = age;
}
const john = new Person('Sourabh', 21); // Error!
When we try to create a new object from the Person class, it will result in failure since arrow functions are not suitable for use as constructors. This limitation is responsible for the error message.
Frequently Asked Questions
Why arrow function is better than function?
Arrow functions are often preferred for their concise syntax, implicit return, and lexical this binding, which simplifies code and avoids issues with traditional function scope and this context in JavaScript.
Are there any performance differences between the arrow and normal functions?
While there is no substantial distinction in performance, arrow functions can contribute to faster code execution due to their brief syntax. Typically, an arrow function is treated similarly to a regular function in terms of functionality.
What is advantages of arrow functions over normal functions?
Arrow functions offer concise syntax, implicitly bind 'this' to the surrounding context, and lack their own 'arguments' object, promoting cleaner and more predictable code compared to traditional functions.
Can I use arrow functions in callback functions?
The use of arrow functions in callback functions is similar to normal functions. But it is necessary to think carefully about the needs of the callback function. We should first consider whether an arrow function or a normal function would be more suitable for the situation.
Conclusion
Understanding the differences between the arrow and regular functions helps us in choosing the right syntax according to our needs. As we know, "this" value inside a regular function is always dynamic and depends on the invocation. But this inside the arrow function is bound lexically and equals to this of the outer function.
If the arrow function has one expression, then the expression will be returned implicitly, even without using the return keyword. Also, you can define methods using the arrow function syntax inside classes. Fat arrow methods bind this value to the class instance.
Anyhow the fat arrow method is invoked, "this" always equals the class instance. It will be useful when the methods are used as callbacks.