Function Declaration and Function Expression are two ways to define functions in JavaScript. They differ in how they are declared and how they are hoisted within the code.
Function Declaration: A function declaration is a statement that defines a named function and makes it available in the current scope. It follows the syntax:
function functionName(parameters) {
}
Key points about function declarations:
They are hoisted: Function declarations are hoisted to the top of the current scope. This means you can use the function before its actual declaration in the code.
They have a named identifier: The function name is mandatory and should be used to invoke the function.
sayHello();
function sayHello() {
console.log("Hello!");
}
sayHello();
Function Expression: A function expression assigns a function to a variable or a property of an object. It follows the syntax:
var variableName = function(parameters) {
};
let sayBye = function() {
console.log("Bye Bye");
}
Key points about function expressions:
They are not hoisted: Function expressions are treated like regular variable assignments, so they are not hoisted. You can only use them after the assignment.
They can be anonymous or named: You can choose to provide a name for the function or leave it anonymous.
sayBye();
let sayBye = function() {
console.log("Bye Bye")
}
sayBye();
sayBye();
^
ReferenceError: Cannot access 'sayBye' before initialization
at Object.<anonymous> (/tmp/QfUWfglX0A.js:11:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
In summary, the main differences between function declarations and function expressions are hoisting behavior and the requirement of a function name. Function declarations are hoisted and require a name, while function expressions are not hoisted and can be anonymous.