A function declaration is a way to define a function in JavaScript. It consists of the function keyword, followed by the function name, a set of parentheses, and a function body. For example:
function greet(name) {
console.log('Hello, ' + name + '!');
}
A function expression is a way to create a function and assign it to a variable. It consists of the function keyword, followed by a set of parentheses and a function body, and is typically assigned to a variable using the assignment operator (=). For example:
let greet = function(name) {
console.log('Hello, ' + name + '!');
}
One key difference between function declarations and function expressions is that function declaration are hoisted, which means that they can be called before they are defined in the code. Function expressions, on the other hand, are not hoisted and must be defined before they can be called.
For example, the following code would work with a function declaration, but would throw an error with a function expression:
greet('John'); // 'Hello, John!'
function greet(name) {
console.log('Hello, ' + name + '!');
}
In summary, a function declaration is a way to define a function in JavaScript that is hoisted, while a function expression is a way to create a function and assign it to a variable that is not hoisted.
Comments (0)