Sobes.tech
Middle+

What is the difference between an arrow function and a function declared with function?

sobes.tech AI

Answer from AI

Arrow functions in JavaScript (and Node.js) differ from regular functions declared with function in several key aspects:

  1. Lexical binding of this

    • In arrow functions, this is taken from the outer lexical context where the function is defined.
    • In regular functions, this depends on how the function is called.
  2. Lack of own arguments object

    • Arrow functions do not have their own arguments; you should use parameters or rest parameters instead.
  3. Cannot be used as constructors

    • Arrow functions cannot be called with new.
  4. No prototype property

    • Arrow functions do not have a prototype property.

Example:

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

obj.regularFunc(); // 42, `this` points to `obj`
obj.arrowFunc();   // undefined or value from the outer context

Thus, arrow functions are convenient for preserving the this context, for example, in callbacks, while regular functions are useful when dynamic this or constructor capabilities are needed.