JavaScript arrow function and function work in a similar manner, but there are specific differences between them syntax difference between arrow function vs function in JavaScript.
Syntax of regular functions:-
let x = function function_name(parameters){
// body of the function
};
Syntax of arrow functions
let x = (parameters) => {
// body of the function
};
- Unlike regular functions, arrow functions do not have their own
this
. - Arguments objects are not available in arrow functions but in regular functions.
- Regular functions are constructible, they can be called using the ‘new’ keyword. However, the arrow functions are only ‘callable’ and not constructible.
Example arrow function vs. normal function in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
//Regular function
let squar = function(x){
return (x*x);
};
console.log("Regular",squar(9));
//Arrow function
var square = (x) => {
return (x*x);
};
console.log("Arrow",square(100));
</script>
</body>
</html>
Output:
Use of this keyword
<script>
let user = {
name: "Hello",
f1:() => {
console.log("World " + this.name); // no 'this' binding here
},
f2(){
console.log("Welcome to " + this.name); // 'this' binding works here
}
};
user.f1();
user.f2();
</script>
Output: World
Welcome to Hello
Availability of arguments objects
Regular function
let user = {
show(){
console.log(arguments);
}
};
user.show(1, 2, 3);
Arrow function
let user = {
show_ar : () => {
console.log(...arguments);
}
};
user.show_ar(1, 2, 3);
Using new keyword
Regular function
let x = function(){
console.log(arguments);
};
new x =(1,2,3);
Arrow function
let x = ()=> {
console.log(arguments);
};
new x(1,2,3);
Here’s a comparison of JavaScript function declarations and arrow functions in a tabular format:
Feature | Function Declaration | Arrow Function |
---|---|---|
Syntax | function name(parameters) | (parameters) => expression |
Hoisting | Yes | No |
Named/Anonymous | Can be both | Always anonymous |
this Behavior | Own this context | Lexical this context |
Constructor | Yes | No |
Use Cases | Methods, Constructors, etc. | Short, one-liner functions, Callbacks in array methods |
Do comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version