Sobes.tech
Middle

What is the difference between an arrow function and a regular function in JavaScript?

sobes.tech AI

Answer from AI

Main differences between arrow functions and regular functions in JavaScript:

  • this context: Arrow functions do not have their own this. They inherit this from the surrounding lexical context. Regular functions have their own this, which depends on how they are called.

  • Lack of arguments: Arrow functions do not have an arguments object. To access arguments, you need to use parameters or the rest operator.

  • Cannot be used as constructors: Arrow functions cannot be called with new.

  • Syntax: Arrow functions are usually shorter and more convenient for concise expressions.

Example:

const obj = {
  value: 42,
  regularFunc: function() { return this.value; },
  arrowFunc: () => this.value
};

console.log(obj.regularFunc()); // 42
console.log(obj.arrowFunc());   // undefined (this does not point to obj)