A function is a named block of code that you write once and run whenever you call its name. It can take inputs (parameters) and hand back a result (a return value).
Here is the smallest useful example, in Python:
def square(number):
return number * number
print(square(5))
Example output:
25
The same function in JavaScript, which is the form MDN uses to introduce functions:
function square(number) {
return number * number;
}
square(5); // 25
Both do the same thing: take a number, multiply it by itself, give the result back. The rest of this article names each part and shows what changes between languages.
The parts of a function
| Part | In square(number) | What it is |
|---|---|---|
| Name | square | How you refer to the function later |
| Parameter | number | A placeholder name for an input, listed in the definition |
| Body | return number * number | The statements that run when the function is called |
| Return value | 25 for input 5 | The result the call hands back to the code that called it |
| Argument | 5 in square(5) | The actual value passed in at the call |
The Python tutorial describes the definition like this: the keyword def introduces a function definition, and it must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body start on the next line and must be indented. JavaScript uses the function keyword, the name, a parenthesized parameter list, and the body in curly braces.
Defining a function is not the same as calling it
MDN states that defining a function does not execute it. The definition only stores the code under a name. The code runs when you call the function with parentheses: square(5). The call runs the body with number set to 5 and gives back 25.
This is why a function can be called many times with different inputs. square(3) returns 9 and square(12) returns 144, from one definition.
Parameters and arguments
People mix these two words up, and in casual talk the difference rarely matters. The distinction is simple. Parameters are the names in the definition. Arguments are the values you supply in the call. MDN's own wording follows it: "The function square takes one parameter, called number", and square(5) calls it "with an argument of 5".
A function can take several parameters, or none. In Python you can also give a parameter a default value, so the caller may leave it out:
def greet(name, greeting="Hello"):
return greeting + ", " + name
print(greet("Ada"))
print(greet("Ada", "Welcome"))
Example output:
Hello, Ada
Welcome, Ada
The Python tutorial says a default value creates a function that can be called with fewer arguments than it is defined to allow. JavaScript has the same idea: function multiply(a, b = 1) is an example on MDN.
What a function returns
The return statement sends a value back to the caller, and the function stops at that point. The caller can store the value, print it, or pass it into another function:
area = square(4)
print(area + 1)
Example output:
17
A function does not have to return anything useful. The Python tutorial's example function fib prints a Fibonacci series and has no return. The tutorial explains that even functions without a return statement do return a value, called None. It shows this:
>>> fib(0)
>>> print(fib(0))
None
Printing and returning are different. print shows text on screen and the program cannot use it afterward. return gives the value to the calling code. A function that only prints cannot be used inside a calculation, so when you want the result, return it. In JavaScript a function with no return gives back undefined; MDN's functions guide does not spell that out, so check the language reference if you rely on it.
Why functions exist
- Reuse. Write the logic once, call it from anywhere. A bug fix then happens in one place.
- Names for ideas.
calculate_tax(price)tells the reader more than six lines of arithmetic. - Testing. A function with clear inputs and a return value can be checked on its own: call it with known arguments and compare the result.
- Composition. One function can call another, so large programs are built from small pieces.
Other ways to write a function in JavaScript
JavaScript has more than one syntax. MDN lists these:
| Form | Example | Note from MDN |
|---|---|---|
| Declaration | function square(number) { return number * number; } | Hoisted, so you can call it before the line where it is written |
| Function expression | const square = function (number) { return number * number; }; | Can be anonymous; convenient when passing a function as an argument |
| Arrow function | const square = (number) => number * number; | Shorter syntax; has no this of its own |
In JavaScript, functions are themselves objects. That means you can assign one to a variable, pass it to another function, or return it from a function. A common case is map, which takes a function and applies it to each item of an array: [1, 2, 3].map((n) => n * n) gives [1, 4, 9].
A mistake to avoid: mutable default values in Python
The Python tutorial carries an explicit warning. A default value is evaluated only once, when the function is defined. If the default is a list or dictionary, every call shares it:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
Example output, as documented in the tutorial:
[1]
[1, 2]
[1, 2, 3]
The tutorial's fix is to use None as the default and create the list inside the function:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
Document what the function does
In Python, the first statement of the body can be a string literal. It becomes the function's docstring, its documentation. The tutorial's fib example begins with """Print a Fibonacci series less than n.""", and the tutorial calls writing docstrings a good practice to make a habit of.
Related ideas
Terminology and syntax vary by language, so check the documentation of the one you use. If you came here from AI tooling, a related concept shares the word: function calling in LLMs lets a model ask your program to run one of your functions.
Frequently asked questions
- What is the difference between a parameter and an argument?
- A parameter is the name listed in a function's definition. An argument is the actual value you pass when you call the function. In square(5), number is the parameter of the definition and 5 is the argument.
- What does a function return if it has no return statement?
- In Python it returns None, which the Python tutorial describes as a rather boring value. In JavaScript a function without a return statement gives back undefined. Either way the caller still gets a value, just not a useful one.
- Does defining a function run it?
- No. Defining a function only stores the code under a name. Nothing inside it executes until you call it, for example with square(5). MDN says this directly: defining a function does not execute it.
- Why use functions instead of copying code?
- A function lets you write a piece of logic once and run it from many places. If the logic needs a fix, you change it in one spot instead of in every copy.