Middle
What are FunctionExpression and FunctionDeclaration? What is their main difference?
sobes.tech AI
Answer from AI
FunctionDeclaration is a function declaration using the function keyword and a function name, for example:
function greet() {
console.log('Hello');
}
FunctionExpression is a function created as an expression and can be anonymous or named, for example:
const greet = function() {
console.log('Hello');
};
The main difference is hoisting:
- FunctionDeclaration is hoisted entirely, so it can be called before its declaration in the code.
- FunctionExpression is hoisted as a variable, but the function itself is only initialized at the point of assignment, so it cannot be called before the assignment.
Example:
sayHi(); // Works
function sayHi() {
console.log('Hi');
}
sayHello(); // Error: sayHello is not a function
const sayHello = function() {
console.log('Hello');
};