Published on

Arrow function vs Regular Function

Authors
  • avatar
    Name
    Khánh
    Twitter

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.
FeatureFunction DeclarationFunction Expression
HoistingYes, can be called before declarationNo, must be defined before calling
ScopeFunction scope or global scope (if not declared within a block)Variable scope
UsageNamed functions for repeated useDynamic function creation, passing functions as arguments, IIFEs

Function declaration/Statement

function greet() {
	...
}

Function Expression

const great = function () {
	...
}

Arrow function do not have arguments

Arrow 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

Arrow Function don't have prototype

// Regular function
function regular(){
}
console.log(regular.prototype); // {constructor: ƒ}

// Arrow function
const arr = () => {
}
console.log(arr.prototype); // undefined

Arrow Function dont' have constructor

// 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

Arrow Function don't have this (call, apply and bind working incorrect)

Regular 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

Arrow Function can't use like Generator function

// 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);
};