Coding

How to Call a Function in Python and JavaScript, With Examples

To call a function, write its name followed by parentheses, and put any inputs (arguments) inside them: add(2, 3). The call runs the function's code and gives back its return value, in Python and JavaScript alike.

Here is the same call in both languages. First Python:

def add(a, b):
    return a + b

result = add(2, 3)
print(result)

Example output:

5

Now JavaScript:

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

const result = add(2, 3);
console.log(result); // 5

The first block of each example defines the function. Only the line with add(2, 3) calls it. If you are not sure what a function is yet, start with what a function is in programming, then come back here.

Defining a function does not run it

MDN states it plainly: defining a function does not execute it. The definition only names the function and records what to do. MDN describes calling as the step that "actually performs the specified actions with the indicated parameters." If you write a function and see no output, check that the file contains a call and not just the definition.

The grammar in the Python language reference shows what a call is: an expression, followed by an opening parenthesis, an optional list of arguments, and a closing parenthesis. The parentheses are what make it a call. Without them you have something else, covered below.

How to call a function with arguments

Arguments are the values you supply in the call. Each one fills a parameter, which is a name in the definition. By position, the first argument fills the first parameter, the second fills the second, and so on.

def greet(name, greeting):
    return greeting + ", " + name

print(greet("Ada", "Hello"))
print(greet("Hello", "Ada"))

Example output:

Hello, Ada
Ada, Hello

Swapping the two arguments swaps the result, because Python matches them by position. Order matters for positional arguments.

Calling with keyword arguments in Python

Python also lets you name the parameter in the call. The tutorial says that by default, arguments may be passed by position or explicitly by keyword. Keyword arguments can come in any order:

print(greet(greeting="Hello", name="Ada"))

Example output:

Hello, Ada

The tutorial lists the rules. In a call, keyword arguments must follow positional arguments. Every keyword must match a parameter the function accepts. No parameter may receive a value more than once. Its own examples of invalid calls, using a function called parrot(voltage, state='a stiff', ...), are:

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

JavaScript has no keyword arguments. Arguments are matched by position only. When a function has many options, JavaScript code usually passes a single object and reads named properties from it, but that is a convention, not a language feature.

Default values: leaving arguments out

A parameter with a default value can be omitted in the call. In Python:

def greet(name, greeting="Hello"):
    return greeting + ", " + name

print(greet("Ada"))
print(greet("Ada", "Welcome"))

Example output:

Hello, Ada
Welcome, Ada

JavaScript supports the same idea: MDN shows function multiply(a, b = 1), so multiply(5) returns 5.

What a call gives back

A call is an expression, so it has a value. You can store it, print it, or use it inside a larger expression:

total = add(2, 3) * 10
print(total)

Example output:

50

The Python reference says a call always returns some value, possibly None, unless it raises an exception. If execution reaches the end of a user-defined function without a return statement, the value is None. A function that only prints therefore gives you None to work with, and print(add(1, 2) + show_total()) would fail if show_total prints but does not return. When you need the result, return it, then call and capture it.

Wrong number of arguments

The two languages treat a mismatch differently.

SituationPythonJavaScript
Too few argumentsTypeError if a parameter has no defaultNo error: the missing parameter is undefined
Too many argumentsTypeError, unless the function accepts *argsNo error: extra arguments are ignored unless the function reads them
Unknown keywordTypeError, unless the function accepts **kwargsNot applicable
Same parameter set twiceTypeErrorNot applicable

The Python reference describes each of these cases as raising a TypeError. The exact message text is not specified in the reference and can change between Python versions, so read the one your interpreter prints. One message that the documentation does show is for a repeated value:

TypeError: function() got multiple values for argument 'a'

For JavaScript, MDN says parameters default to undefined. Its example is a multiply(a, b) function: with no value for b, the expression a*b would normally return NaN. The call does not fail, the result is just wrong, so a JavaScript function that depends on all its inputs needs a default value or an explicit check.

Why nothing happens when you leave out the parentheses

This is a very common beginner mistake. In Python, the name alone refers to the function object:

>>> add
<function add at 0x7f3c2a1b5e50>
>>> add(2, 3)
5

The memory address in the first line will differ on your machine (example output). The Python tutorial makes the same point with its fib function, where fib alone displays a function object and f = fib followed by f(100) works, because other names can point to the same function. Only the form with parentheses calls it.

The reverse mistake matters too. When you hand a function to something else that will call it later, leave the parentheses off. MDN's map example passes a function as an argument, and map calls it internally for each item. In JavaScript:

const numbers = [1, 2, 3];

function double(n) {
  return n * 2;
}

console.log(numbers.map(double));   // [2, 4, 6]
console.log(numbers.map(double())); // TypeError

The second line calls double() immediately with no argument, gets NaN back, and hands that to map, which then fails because NaN is not a function. Pass double when you want map to do the calling, and write double(4) when you want the result now.

Calling a function that belongs to an object

MDN defines a method as a function that is a property of an object. You call it with a dot, then the name, then parentheses. MDN's pet example calls pet.getName() on an object that createPet("Vivie") returned. Python uses the same shape:

print("hello".upper())
print("a,b,c".split(","))

Example output:

HELLO
['a', 'b', 'c']

The object before the dot is passed to the method automatically. You supply only the remaining arguments inside the parentheses.

Calling a function before it is defined

MDN says functions must be in scope when they are called, and that a function declaration can be hoisted, so the call can appear above it in the code. This works in JavaScript:

console.log(square(5)); // 25

function square(n) {
  return n * n;
}

MDN adds that hoisting only works for declarations, not for function expressions. Assign the function to a const and call it earlier, and you get ReferenceError: Cannot access 'square' before initialization. The details are in JavaScript function expression vs declaration.

Python has no hoisting. A name exists only after the def statement has run. A call at the top of a script to a function defined lower down fails. A call inside another function body is fine as long as both definitions have run by the time the outer function is called.

Calling a function inside another function call

Because a call is an expression, you can nest calls. The inner call runs first and its return value becomes the outer call's argument:

print(add(add(1, 2), 4))

Example output:

7

Here add(1, 2) returns 3, then add(3, 4) returns 7, then print shows it. Reading nested calls from the inside out makes them easy to follow.

If the call still fails

  • Nothing prints. Check that you called the function and that it returns or prints something. A bare name does not run it.
  • A TypeError about arguments in Python. Compare the call with the definition: count the required parameters, check the keyword spellings, and make sure no value is given both by position and by keyword.
  • NaN or undefined in JavaScript. A parameter probably received no argument. Log the arguments at the top of the function.
  • A NameError in Python or a ReferenceError in JavaScript. The name is not defined yet at the point of the call, or it is spelled differently. Check the order of the definition and the call.

Frequently asked questions

Why does my function not run when I write its name?
Writing only the name, such as add, refers to the function object without running it. You need parentheses after the name, as in add(2, 3), to call it. In Python, printing the bare name shows something like <function add at 0x...> instead of a result.
Can I call a function before I define it?
In JavaScript you can for a function declaration, because declarations are hoisted to the top of their scope. You cannot for a function expression assigned with const, which throws a ReferenceError. In Python the function must be defined by the time the call actually runs, though the call can sit inside another function that is defined earlier.
What happens if I pass too few arguments?
Python raises a TypeError when a parameter without a default value gets no argument. JavaScript does not raise an error: the missing parameter is undefined inside the function, which often turns into NaN or another wrong result later.
What is the difference between passing a function and calling it?
map(f, items) passes the function f itself, and map calls it later. map(f(), items) calls f right now and passes whatever f returned. Leave the parentheses off when you want another function to do the calling.

Sources