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:
-
Lexical binding of
this- In arrow functions,
thisis taken from the outer lexical context where the function is defined. - In regular functions,
thisdepends on how the function is called.
- In arrow functions,
-
Lack of own
argumentsobject- Arrow functions do not have their own
arguments; you should use parameters or rest parameters instead.
- Arrow functions do not have their own
-
Cannot be used as constructors
- Arrow functions cannot be called with
new.
- Arrow functions cannot be called with
-
No
prototypeproperty- Arrow functions do not have a
prototypeproperty.
- Arrow functions do not have a
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.