Skip to content

Function

In one line

A function is a reusable block of code that performs a task, optionally taking inputs and returning a result.

In simple words

A function is a named, reusable block of code. You write it once, then call it by name whenever you need it — optionally passing in inputs (parameters) and getting a result (return value) back.

Functions help you avoid repeating yourself (the DRY principle). Instead of writing the same calculation in five places, you write it once as a function and call it five times. If the logic changes, you update only the function.

Functions are the primary way programmers organize and structure code. A typical program is a collection of functions that call each other, each focused on one small job.

Example

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

console.log(add(2, 3));  // 5
console.log(add(10, 20)); // 30

add is a function that takes two parameters a and b and returns their sum.

How it works

  1. Define the function with a name and a body (the code to run).
  2. Call the function by name, optionally passing arguments.
  3. The function runs its body, using the arguments as inputs.
  4. If the function has a return statement, it sends a value back to the caller.

Common confusions

  • Confused with: method

    The difference: A function stands on its own; a method is a function that belongs to an object and is called with a dot (e.g. array.push()). All methods are functions, but not all functions are methods.

Related terms

Related Resources

Related Lessons

  • Functions

    Learn how to define and call functions

Related Projects

Learn the fundamentals

Deepen your understanding with structured lessons on this topic.

View lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary