Sobes.tech
Junior — Middle

What are the differences between arrow functions and regular functions in JavaScript?

sobes.tech AI

Answer from AI

Arrow functions in JavaScript differ from regular functions in several key aspects:

  • this context: In arrow functions, this is lexically bound to the context where the function was declared. In regular functions, this is determined at call time and can change.
  • No own arguments: Arrow functions do not have their own arguments object. To access arguments, use parameters or rest operator.
  • Cannot be used as constructors: Arrow functions cannot be called with new and do not have a [[Construct]] internal method.
  • No prototype: Arrow functions do not have a prototype property.

Example:

const obj = {
  value: 42,
  regularFunc: function() {
    console.log(this.value); // 42
  },
  arrowFunc: () => {
    console.log(this.value); // undefined, because `this` is from outer scope
  }
};

obj.regularFunc();
obj.arrowFunc();