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:
-
thiscontext: In arrow functions,thisis lexically inherited from the surrounding context, meaning it refers to the same object as in the outer scope. In traditional functions,thisis determined at the time of invocation and depends on how the function was called. -
Absence of
arguments: Arrow functions do not have their ownargumentsobject. To access arguments, you need to use parameters or rest parameters. -
Cannot be used as constructors: Arrow functions cannot be called with
newand do not have their ownprototype. -
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)