Problem Statement
What is the main difference between arrow functions and regular functions?
Explanation
The main difference is that arrow functions do not have their own this binding.
They inherit this from the parent scope where they are defined, called lexical this.
Regular functions have their own this which depends on how the function is called.
Arrow functions also do not have arguments object, cannot be used as constructors with new, and do not have prototype property.
They provide shorter syntax and are commonly used for callbacks and functional programming patterns.
Code Solution
SolutionRead Only
// Arrow function - lexical this
const obj = {
name: 'Object',
regularFunc: function() {
console.log(this.name); // 'Object'
},
arrowFunc: () => {
console.log(this.name); // undefined (uses parent scope this)
}
};
obj.regularFunc(); // 'Object'
obj.arrowFunc(); // undefined
// Arrow syntax variations
const add1 = (a, b) => { return a + b; };
const add2 = (a, b) => a + b; // Implicit return
const square = x => x * x; // Single param, no parentheses
const greet = () => 'Hello'; // No params
// Cannot use as constructor
const Person = (name) => { this.name = name; };
// const p = new Person('John'); // TypeError
// Use cases
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // Clean callback
console.log(doubled); // [2, 4, 6]