No announcement
 

Function Declarations vs. Expressions

Function Declarations

A function declaration is a way to define a named function in JavaScript. It begins with the function keyword, followed by the function name, a list of parameters (if any), and the function body enclosed in curly braces {}. Function declarations are hoisted in JavaScript, meaning they can be called before their actual declaration in the code.

Example:

function_declaration.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Function Declaration Example</title>
</head>
<body>

<h2>JavaScript Function Declaration:</h2>
<script>
// Function Declaration
function greet(name) {
  return "Hello, " + name + "!";
}

let message = greet("John");
console.log(message); // Output: Hello, John!
</script>

</body>
</html>

Output
Hello, John!

In this example, we defined a function named greet using the function declaration syntax. The function takes a parameter name and returns a greeting message. We then called the function with the argument "John" and stored the result in the message variable. The output displays "Hello, John!" as expected.

Function Expressions

A function expression is another way to define a function in JavaScript. It involves assigning a function to a variable. Function expressions are not hoisted, meaning they must be defined before they are used.

Example:

function_expression.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Function Expression Example</title>
</head>
<body>

<h2>JavaScript Function Expression:</h2>
<script>
// Function Expression
let greet = function(name) {
  return "Hello, " + name + "!";
};

let message = greet("Alice");
console.log(message); // Output: Hello, Alice!
</script>

</body>
</html>

Output
Hello, Alice!

In this example, we defined a function expression by assigning an anonymous function to the greet variable. The function takes a parameter name and returns a greeting message. We then called the function with the argument "Alice" and stored the result in the message variable. The output displays "Hello, Alice!" as expected.

Key Differences:

The main differences between function declarations and expressions are:

  • Hoisting: Function declarations are hoisted, so they can be called before their actual declaration in the code. Function expressions are not hoisted, so they must be defined before they are used.
  • Names: Function declarations require a name for the function, whereas function expressions can be anonymous (i.e., have no name) or have a name if assigned to a variable.

Both function declarations and expressions are essential tools for creating reusable and modular code in JavaScript. The choice between them depends on the specific use case and code organization needs.