Junior
What is a function expression and a function declaration?
sobes.tech AI
Answer from AI
In JavaScript, there are two main ways to create functions: function declaration and function expression.
- Function declaration is the classic way, where a function is declared with the
functionkeyword and a name:
function greet() {
console.log('Hello');
}
Function declarations are hoisted to the top of their scope, so they can be called before their definition in the code.
- Function expression is when a function is created as part of an expression and can be anonymous or named:
const greet = function() {
console.log('Hello');
};
Function expressions are not hoisted, so they cannot be called before they are defined in the code.
The difference in scope and hoisting affects the order of invocation and accessibility of functions. Function expressions are often used to create closures or pass functions as arguments.