Member-only story
Difference Between Regular Functions and Arrow Functions
In JavaScript, there are two ways to define functions: regular functions and arrow functions. The main difference between them is the way they handle the this
keyword and their syntax. In this answer, we'll take a closer look at both of them with examples.
Regular Functions: Regular functions in JavaScript are defined using the function
keyword. They can be defined as function declarations or function expressions.
Here is an example of a function declaration:
function sayHello(name) {
console.log(`Hello ${name}!`);
}
And here is an example of a function expression:
const sayHello = function(name) {
console.log(`Hello ${name}!`);
}
Regular functions have their own this
binding. When a regular function is called, this
refers to the object that called the function. For example:
const person = {
name: 'John',
sayHello: function() {
console.log(`Hello, my name is ${this.name}`);
}
}
person.sayHello(); // output: "Hello, my name is John"
Arrow Functions: Arrow functions were introduced in ECMAScript 6 as a more concise way to define functions. They use the =>
syntax and do not have their own this
binding. Instead, they use the this
value of the enclosing lexical…