- Published on
Arrow function vs Regular Function
- Authors
- Name
- Khánh
Function Types
These are two types of function in javascript:
- Function declaration/Statement: This is the normal way to declare a function. The function can be called before or after the declaration due to hoisting.
- Function Expression: The function was created and saved in the variables - without hoisting.
Feature | Function Declaration | Function Expression |
---|---|---|
Hoisting | Yes, can be called before declaration | No, must be defined before calling |
Scope | Function scope or global scope (if not declared within a block) | Variable scope |
Usage | Named functions for repeated use | Dynamic function creation, passing functions as arguments, IIFEs |
Function declaration/Statement
function greet() {
...
}
Function Expression
const great = function () {
...
}
arguments
Arrow function do not haveArrow function can't get all the input into one variable like arguments
// Regular function
function findMaxNumber(){
return Math.max(...arguments);
}
console.log(findMaxNumber(1,2,3,5,5,6,7,100)) // 100
prototype
Arrow Function don't have// Regular function
function regular(){
}
console.log(regular.prototype); // {constructor: ƒ}
// Arrow function
const arr = () => {
}
console.log(arr.prototype); // undefined
constructor
Arrow Function dont' have// Regular function
function test(){}
const x = new test();
console.log(x); // test {}
// Arrow function
const testArrowFn = () => {};
const y = new testArrowFn(); // VM87094:2 Uncaught TypeError: testArrowFn is not a constructor
this (call, apply and bind working incorrect)
Arrow Function don't haveRegular function
const user = {
username: "hi",
getUsername: function(){
return this.username
}
}
const getUsernameFn = user.getUsername;
console.log(getUsernameFn()); // undefined
console.log(user.getUsername()); // hi
Arrow function
const user = {
username: "hi",
getUsername: () => {
return this.username;
}
}
const getUsernameFn = user.getUsername;
console.log(getUsernameFn()); // undefined
console.log(user.getUsername()); // undefined
Generator function
Arrow Function can't use like// Arrow Function
const generatorArrowFn = *() => {}
//Uncaught SyntaxError: Unexpected token '*'
Can't duplicated name in arrow function
Arrow function designed for the lightweight and easy to use purpose.
// Regular function allows duplicate parameter names
function add(num1, num1) {
console.log(num1 + num1); // Output: 2
}
add(1, 1);
// Arrow function does not allow duplicate parameter names
const multiply = (num, num) => { // Syntax error
console.log(num * num);
};