JavaScript Functions

A JavaScript function is a reusable block of code designed to perform a particular task. Functions are one of the fundamental building blocks of JavaScript, allowing you to organize code, avoid repetition, and create modular programs. Functions are executed when they are called (invoked).

Function Syntax

Functions are defined using the function keyword, followed by a name, parentheses for parameters, and curly braces containing the code to execute. The basic syntax is: function name(parameters) { code }. This is called a function declaration and is one of the most common ways to create functions in JavaScript.

Function names follow the same naming rules as variables: they can contain letters, digits, underscores, and dollar signs, must start with a letter, underscore, or dollar sign, and are case-sensitive. By convention, function names use camelCase and are descriptive verbs or verb phrases that indicate what the function does (like calculateTotal, getUserData, or validateEmail).

Parameters are listed inside the parentheses after the function name. Parameters are like placeholders or variables that will receive values (called arguments) when the function is called. You can have zero parameters, one parameter, or multiple parameters separated by commas. Parameters are local to the function—they only exist within the function's scope.

The code to execute is placed inside curly braces { }. This code block (called the function body) contains the statements that run when the function is called. The function body can contain any valid JavaScript code: variable declarations, conditional statements, loops, and calls to other functions. The code executes in order from top to bottom.

Functions can return values using the return keyword followed by the value or expression to return. The return statement ends function execution immediately and sends a value back to the code that called the function. If no return statement is present, or if return is used without a value, the function returns undefined. You can use the returned value by assigning it to a variable or using it in an expression.

To use a function, you call (or invoke) it by writing its name followed by parentheses containing any arguments: functionName(arguments). When a function is called, JavaScript jumps to the function's code, executes it with the provided arguments, and then returns to where it was called from. Functions can be called multiple times with different arguments, making them reusable.

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

// Calling the function
let message = greet("John");
console.log(message); // "Hello, John!"

// Function with multiple parameters
function add(a, b) {
  return a + b;
}

let sum = add(5, 3);
console.log(sum); // 8

// Function without return
function sayHello() {
  console.log("Hello!");
}

sayHello(); // Prints "Hello!"

Function Expressions

Functions can be stored in variables using function expressions. Instead of declaring a named function, you assign a function to a variable: const myFunc = function() { }. The function itself can be anonymous (unnamed) since you reference it through the variable name. Function expressions are values, so they can be assigned, passed around, and manipulated like any other value.

Function expressions can be anonymous (without a name) or named. Anonymous function expressions are more common: const square = function(x) { return x * x; }. Named function expressions include a name after the function keyword, which is useful for recursion or debugging: const factorial = function fact(n) { return n <= 1 ? 1 : n * fact(n-1); }.

When a function is stored in a variable, you don't need to give the function a name because you call it using the variable name. Write "multiply(3, 4)" not "function multiply(a, b)" when it's stored in a const multiply variable. The variable name effectively becomes the function's name for calling purposes.

Function expressions are not hoisted like function declarations. Function declarations are hoisted to the top of their scope, meaning you can call them before they're defined in the code. Function expressions are not—they're only available after the line where they're assigned. Calling a function expression before its assignment results in an error.

Because functions are first-class objects in JavaScript, functions can be passed as arguments to other functions. This enables powerful patterns like callbacks, higher-order functions, and functional programming techniques. For example, array methods like map, filter, and forEach accept functions as arguments. You can write code that operates on functions, creating flexible and reusable abstractions.

// Function expression
const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 5)); // 20

// Anonymous function
const square = function(x) {
  return x * x;
};

// Function as argument
function calculate(operation, a, b) {
  return operation(a, b);
}

const result = calculate(multiply, 3, 4);
console.log(result); // 12