Sobes.tech
Junior — Middle

What is the difference between using an arrow function and a traditional function when declaring in JavaScript?

sobes.tech AI

Answer from AI

Arrow functions in JavaScript differ from traditional functions in several key ways:

  • this context: In arrow functions, this is lexically inherited from the surrounding context, meaning it refers to the same object as in the outer scope. In traditional functions, this is determined at the time of invocation and depends on how the function was called.

  • Absence of arguments: Arrow functions do not have their own arguments object. To access arguments, you need to use parameters or rest parameters.

  • Cannot be used as constructors: Arrow functions cannot be called with new and do not have their own prototype.

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

Example:

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

obj.traditionalFunc(); // `this` points to `obj`
obj.arrowFunc(); // `this` points to the outer context (e.g., window or undefined in strict mode)