Functions are the backbone of JavaScript programming, allowing for modular, reusable, and maintainable code. Understanding the different ways to define and use functions is crucial for any JavaScript developer. In this chapter, we will explore function declarations, function expressions, arrow functions, immediately invoked function expressions (IIFE), and higher-order functions.

Function Declarations

Function declarations are a fundamental way to define functions in JavaScript. They are hoisted, meaning you can call them before they appear in the code.

Syntax:

function functionName(parameters) {
  // code to be executed
}

Example:

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet('Alice')); // Output: Hello, Alice!

In this example, the greet function takes a name parameter and returns a greeting message. Because of hoisting, you can invoke greet anywhere in your script, even before its declaration.

Function Expressions

Function expressions involve defining a function and assigning it to a variable. These functions are not hoisted, meaning they cannot be called before they are defined.

Syntax:

const functionName = function(parameters) {
  // code to be executed
};

Example:

const greet = function(name) {
  return `Hello, ${name}!`;
};

console.log(greet('Bob')); // Output: Hello, Bob!

Here, the function is assigned to the variable greet. This method allows for greater flexibility, such as defining functions conditionally.

Arrow Functions

Arrow functions, introduced in ES6, provide a more concise syntax for writing functions. They also have lexical scoping for this, making them ideal for certain contexts like callbacks and array methods.