Middle
What are the ways to declare functions in JavaScript? How does function declaration differ from function expression? How does arrow function differ from function declaration?
sobes.tech AI
Answer from AI
In JavaScript, there are several ways to declare functions:
- Function Declaration:
function foo() {
return 'bar';
}
The function is hoisted to the top of its scope, so it can be called before its declaration.
- Function Expression:
const foo = function() {
return 'bar';
};
The function is created at runtime and is not hoisted, so it cannot be called before its declaration.
- Arrow Function:
const foo = () => 'bar';
Differences of arrow functions from function declarations:
- They do not have their own
this, inheriting it from the outer scope. - They do not have
arguments,super, ornew.target. - They cannot be used as constructors (cannot be called with
new). - They have a more concise syntax.
Thus, the choice of declaration method depends on the context and the desired behavior of the function.