Junior
What is the difference between the two ways of defining a function?
sobes.tech AI
Answer from AI
The main difference is the this context.
| Method of defining a function | Difference |
|---|---|
function declaration |
The this context is determined by how the function was called. It is hoisted before execution. |
arrow function |
The this context is inherited from the surrounding (lexical) context. It is not hoisted (no hoisting). |
// function declaration
function regularFunction() {
console.log(this); // `this` depends on the call
}
// arrow function
const arrowFunction = () => {
console.log(this); // `this` is inherited from the context where the function is defined
};
Arrow functions also do not have their own arguments object (it is taken from the outer context) and cannot be used as constructors with the new operator.