1. Function Declarations

A function declaration is the most common way to define a function in JavaScript. It is hoisted, meaning it is available even before the code appears in the script.

function greet(name) {
  return "Hello, " + name + "!";
}

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

2. Function Expressions

A function expression is when a function is assigned to a variable. Unlike function declarations, function expressions are not hoisted and must be defined before they are used.

const greet = function(name) {
  return "Hello, " + name + "!";
};

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

3. Arrow Functions

Arrow functions provide a shorter syntax for writing functions. They are especially useful when working with anonymous functions or callbacks.

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

console.log(greet("Charlie")); // Output: Hello, Charlie!
      

4. Function Parameters and Return Values

Functions can take parameters and return values. You can define default values for parameters in case they are not provided by the caller.

function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5));   // Output: 5 (because b defaults to 1)
console.log(multiply(5, 3)); // Output: 15
      

5. Higher-Order Functions

JavaScript functions can accept other functions as arguments or return functions themselves. These are known as higher-order functions.

function add(a, b) {
  return a + b;
}

function applyOperation(fn, x, y) {
  return fn(x, y);
}

console.log(applyOperation(add, 2, 3)); // Output: 5