In programming, particularly in languages like JavaScript, functions are fundamental constructs used to encapsulate a block of code that can be called and executed at any point in a program. There are two primary ways to define functions: function declarations and function expressions. Let me explain each with an example:
Function Declaration
A function declaration is a statement that defines a named function. It’s typically hoisted to the top of its scope, which means you can call the function before it appears in the code.
function functionName(parameters) { // function body // code to be executed return value; // optional }
Example
// Function declaration function greet(name) { return `Hello, ${name}!`; } // Calling the function console.log(greet('John')); // Output: Hello, John!
In this example:
greet
is the function name.name
is a parameter that the function expects.- The function returns a greeting message using the
return
statement.
Function Expression
A function expression defines a function as part of an expression, typically by assigning it to a variable. Unlike function declarations, function expressions are not hoisted, meaning they cannot be called before they are defined in the code.
const functionName = function(parameters) { // function body // code to be executed return value; // optional };
Example:
// Function expression const greet = function(name) { return `Hello, ${name}!`; }; // Calling the function console.log(greet('Emily')); // Output: Hello, Emily!
In this example:
greet
is a variable storing an anonymous function.name
is a parameter passed to the function.- The function returns a greeting message.
Key Differences:
- Hoisting: Function declarations are hoisted, while function expressions are not.
- Usage: Function declarations can be called before they are defined in the code (due to hoisting), but function expressions must be defined before they are called.
Both function declarations and function expressions are powerful tools in programming, each with its own use cases and implications for scope and hoisting.