JavaScript Functions: How They Work and When to Use Them

Formulas & functions · Updated November 22, 2026

In JavaScript, a function is a reusable block of code that can receive values, perform work, and optionally return a result. Functions help organize programs into smaller tasks, and they can also be passed to other functions, stored in variables, or run later in response to an event.

What a JavaScript function does

A function gives a named or otherwise accessible unit of behavior to your program. Instead of writing the same calculation repeatedly, you can define it once and call it wherever needed. A function can accept inputs called parameters, use those inputs in its body, and send a value back with return. It can also perform an action, such as displaying a message or updating data, without returning a useful value.

Here is a small function declaration:

function addTax(price, rate) {
  return price * (1 + rate);
}

const total = addTax(20, 0.1);

In this example, price and rate are parameters: names the function uses for incoming values. The values 20 and 0.1 are arguments supplied in the call. The function returns 22, which is assigned to total. Defining a function does not usually run its body; calling it with parentheses does.

Functions are values in JavaScript. That means a function can be assigned to a variable, placed in an object, returned from another function, or passed as an argument. This flexibility is central to event-driven code, array processing, and many JavaScript libraries.

Function declarations, expressions, and arrow functions

JavaScript offers several ways to create a function. A function declaration gives it a name directly:

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

A function expression creates a function as part of an expression, often assigning it to a variable. The function may have a name, but it does not have to:

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

Declarations and expressions differ in when they can be used. Function declarations are initialized when their surrounding scope is set up, so they can generally be called earlier in that scope than the line where they appear. A function expression assigned to a const or let variable cannot be used before that variable is initialized. This is one reason many developers place definitions before their first use, even when hoisting would allow otherwise.

Arrow functions provide a shorter expression syntax, especially useful for brief callbacks:

const double = number => number * 2;
const greet = name => `Hello, ${name}`;

When an arrow function has one parameter, its parentheses can be omitted; with no parameters or multiple parameters, parentheses are needed. An expression body implicitly returns its expression. If the body uses braces, it is a statement block and needs an explicit return to produce a value:

const double = number => {
  return number * 2;
};

Arrow functions are not simply shorter versions of every other function. They do not create their own this value, and they cannot be called with new as constructors. Use them when their lexical this behavior fits the task; use a regular function when you need a function’s own this or constructor behavior.

Parameters, arguments, and return values

Parameters let a function work with different inputs instead of fixed values. If a caller leaves a parameter out, its value is normally undefined. You can provide a default for missing or explicitly undefined arguments:

function greet(name = 'friend') {
  return `Hello, ${name}`;
}

JavaScript also supports rest parameters. A rest parameter gathers remaining arguments into an array and must be the last parameter:

function sum(...numbers) {
  return numbers.reduce((total, number) => total + number, 0);
}

Calling sum(2, 3, 4) gives 9. Destructuring can make object or array inputs easier to work with, for example function showUser({ name }) { return name; }. Such a function expects an object argument; passing undefined without a default object will cause an error during destructuring.

A function stops and gives a result when it reaches return. A return with no expression, or reaching the end of the body without a return, produces undefined. This is different from printing or logging a value: console.log displays information for a developer, but it does not return that displayed value from the function. A function can also return an object, array, or another function, not only a number or string.

Scope, local variables, and closures

Scope determines where a variable name can be accessed. Variables declared with let and const inside a function are local to that function body, and variables declared inside a block are limited to that block. A function can read names from an enclosing scope, but code outside the function cannot directly read its local variables. Keeping temporary values local reduces accidental interference between parts of a program.

A closure occurs when a function retains access to variables from the scope in which it was created, even after that outer function has finished running. For example:

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

const nextCount = makeCounter();
nextCount(); // 1
nextCount(); // 2

The inner function keeps access to count; each call updates the same variable captured by that returned function. Closures are useful for maintaining private state, creating specialized functions, and implementing callbacks. They do not automatically copy every outer value into a separate snapshot: they retain access to the relevant lexical environment, so later changes to a captured binding can be observable.

Functions, methods, and the meaning of this

A method is a function used as a property of an object. For example, in user.describe(), describe is called as a method of user. With a regular function, the value of this is determined by how the function is called, not simply by where it was written. In this method call, this refers to the object before the dot.

const user = {
  name: 'Mina',
  describe() {
    return `User: ${this.name}`;
  }
};

If you take a method out of its object and call it as a plain function, it may no longer receive the object as this; the exact result also depends on strict mode and the calling context. Arrow functions behave differently: they inherit this from the surrounding scope and do not establish their own. This can be helpful inside a callback that needs the enclosing this, but is often unsuitable for defining an object method that expects this to mean the object.

Callbacks and higher-order functions

A callback is a function passed to other code so it can be called at an appropriate time. The receiving function might call it immediately, once per item, after a delay, or after an event. For example, map takes a callback and uses its returned value to build a new array:

const prices = [5, 10, 15];
const doubled = prices.map(price => price * 2);

Here doubled is [10, 20, 30]. By contrast, forEach calls a callback for each item but does not create a transformed array from its return values. Choosing between them depends on whether you want a new array or simply want to perform an action for each item.

A higher-order function is a function that accepts one or more functions as arguments, returns a function, or does both. Array methods such as map, filter, and reduce are common examples. In browser code, event listeners also use callbacks: a function can be supplied to run when a user clicks a button. A callback may run later, so variables it closes over and the order of operations matter. When asynchronous callbacks are involved, promises and async/await can make the sequence of work easier to follow.

Async functions and generators

An async function is designed for asynchronous work. It always returns a promise, even if its code returns an ordinary value. Inside it, await pauses that function’s progress until a promise settles, allowing later lines to use the fulfilled value. It does not block the entire JavaScript environment while waiting.

async function loadProfile() {
  const response = await fetch('/profile');
  if (!response.ok) {
    throw new Error('Request failed');
  }
  return response.json();
}

The caller can use await loadProfile() from an async context or attach .then() and .catch() to the returned promise. Errors thrown inside an async function cause its promise to reject, so callers should handle failures when appropriate. Also, a network response can indicate failure through its status without making fetch reject; checking response.ok addresses that case.

Generator functions, written with function*, are another specialized form. Calling one returns an iterator; its execution can pause at yield and continue when the iterator is advanced. Generators can represent sequences that are produced on demand, though ordinary functions and async functions are more common in everyday application code.

Choosing a function form and avoiding common problems

Choose based on behavior and readability, not just character count. A declaration is often clear for a reusable, named operation. An arrow function is convenient for a short callback or a function that should inherit the surrounding this. A regular function expression can be appropriate when you need a function value with its own call-time this. Longer logic can be easier to understand as a named function with a block body than as a deeply nested one-line arrow.

Common mistakes include confusing a function reference with a function call, forgetting to return a value, and assuming that console.log returns what it prints. These examples show the difference:

function getAnswer() {
  return 42;
}

const functionValue = getAnswer; // the function itself
const answer = getAnswer();      // the result, 42

Another frequent issue is accidentally calling a function while assigning an event handler or callback. If an API expects a function to run later, pass the function itself, such as button.addEventListener('click', handleClick), rather than handleClick(), which runs it immediately and passes its result. When extra arguments are needed, a wrapper such as () => handleClick(id) can defer the call.

Functions are easier to maintain when they have focused responsibilities and clear inputs and outputs. A function that both calculates a value and changes unrelated global state is harder to reuse and test than one whose purpose is narrow. This does not mean every function must be pure: user interfaces and applications need side effects, including network requests and updates. Making side effects visible and limiting unnecessary shared state simply makes behavior easier to reason about.

Frequently Asked Questions

Are JavaScript functions objects?
Functions are callable values and are objects in the broad JavaScript sense: they can be stored, passed around, and have properties. Some function forms have special restrictions, and arrow functions, for example, cannot be used as constructors.

What is the difference between a parameter and an argument?
A parameter is the named variable in a function definition, such as name in function greet(name). An argument is the value provided when calling it, as in greet('Sam').

Why does my function return undefined?
It may have no return statement, or execution may reach the end of the function without one. Add an explicit return where a result is required. Logging a value does not return it.

When should I use an arrow function instead of function?
Use an arrow when its shorter syntax and inherited this suit the task, commonly in callbacks. Choose a regular function when you need its own this, need to use it as a constructor, or find the traditional form clearer.

Can a JavaScript function return more than one value?
Not as multiple separate return values. It can return one array or object containing several values, which the caller can then unpack with destructuring.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.