An Interest In:
Web News this Week
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
The Difference Between Regular Functions and Arrow Functions
Arrow function also called fat arrow function is a new feature introduced in ES6 that is a more concise syntax for a writing function expression.
Following are the main differences:
- Syntax
- Arguments binding
- Use of this keyword
- Using a new keyword
- No duplicate named parameters
1) Syntax:
A developer can get the same result as regular functions by writing a few lines of code using arrow functions.
Curly brackets are not required if only one expression is present.
let add = (x, y) => x + y;
If theres only one argument, then the parentheses are not required either:
let squareNum = x => x * x;
2) Arguments binding
Arrow functions do not have arguments binding.
Regular Function
// Object with Regular function.let getData = {// Regular function showArg:function(){ console.log(arguments); } }getData.showArg(1,2,3); // output {0:1,1:2,2:3}
Output
Arrow Function:
// Object with Arrow function.let getData = {// Arrow function showArg:()=>console.log(arguments)}getData.showArg(1,2,3); // Uncaught ReferenceError: arguments is not defined
Output
3) Use of this keyword
unlike Regular functions, arrow function does not have their own "this" keyword.
The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.
4) Using a new keyword
Regular functions created using function declarations or expressions are constructible and callable. Regular functions are constructible; they can be called using the new keyword.
However, the arrow functions are only callable and not constructible, i.e., arrow functions can never be used as constructor functions.
let add = (x, y) => console.log(x + y);new add(2,3);
5) No duplicate named parameters
Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.
However, We can use duplicate named parameters for regular function in non-strict mode.
Original Link: https://dev.to/vandnakapoor19/the-difference-between-regular-functions-and-arrow-functions-j7d
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To