Appearance
JavaScript Function Declaration
In JavaScript there are two ways to declare functions: Regular Functions and Arrow Functions.
Here are some differences:
Arrow Function is More Concise
js
// arrow function
const add = (a, b) => a + b;
// regular function
function add(a, b) {
return a + b;
}Lexical this binding vs Dynamic this binding:
js
// arrow function `this` is lexically bound to the surrounding scope.
const handleClickArrow = () => {
console.log(`this.color:`, this.color);
};
// regular function `this` is dynamic.
function handleClickRegular() {
console.log(`this.color:`, this.color);
}
const greenButton = document.getElementById('myButton');
greenButton.color = 'green'
greenButton.onclick = handleClickArrow; // this.color: 'undefined'
greenButton.onclick = handleClickRegular; //this.color: 'green'Arrow function auto-binds this in a class
js
class Person {
constructor(age) {
this.age = age;
this.getAgeRegular = this.getAgeRegular.bind(this)
}
getAgeArrow = () => {
return this.age;
}
getAgeRegular() {
return this.age;
}
}
let p = new Person(21);
console.log(p.getAgeArrow()) // 21
console.log(p.getAgeRegular()) // 21Regular Functions can be called before initialization (Hoisted)
js
add(1, 2) // 3 hoisted
function add(a, b) {
return a + b;
}js
add(1,2) // Uncaught ReferenceError: add is not defined
const add = (a, b) => a + bRegular Functions can be used as constructors with new
js
function Person(age) {
this.age = age
}
const PersonArrow = (age) => this.age = age;
const sam = new Person(20) // ✅
const john = new PersonArrow(20) // ❌ ReferenceError: PersonArrow is not definedArrow Functions lack arguments object
js
function regular() {
console.log(arguments);
}
const arrow = () => {
console.log(arguments)
}
regular(1,2,3) // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
arrow(1,2,3) // Uncaught ReferenceError: arguments is not definedjs
// arrow function encourages a more concise and modern syntax
const sum = (...args) => args.reduce((acc, val) => acc + val, 0);
console.log(sum(1,2,3)) // 6
vs
// regular function
function sum() {
return Array.prototype.reduce.call(arguments, (acc, val) => acc + val, 0);
}
console.log(sum(1,2,3)) // 6