What a function is and why you need one

A function is a block of code that does one specific job. Instead of writing the same lines over and over, you write them once inside a function, give that function a name, and then call that name whenever you need that job done. Functions make your code shorter, easier to read, and much easier to fix when something breaks.

Every programming language has functions, though they may be called different things — some languages call them methods, procedures, or subroutines. The basic idea is the same: you bundle related code together, label it, and reuse it.

Key Takeaways

  • A function is a named block of code that performs one task and can be reused anywhere in your program.
  • You define a function once with a name and parameters, then call it by name whenever you need it to run.
  • Functions can take input (parameters) and return output (a result), or do neither, depending on what the job requires.
  • The syntax for writing a function changes between languages, but the structure — name, parameters, body, return — stays the same.
  • Organizing your code into functions makes it easier to test, debug, and reuse across different parts of your program.

The basic structure: name, parameters, and body

Every function has three parts. The name is what you call it by — something short that describes what it does, like calculateTotal or sendEmail. The parameters are the inputs the function needs to do its job — they go in parentheses after the name. The body is the actual code that runs when you call the function.

In Python, a function that adds two numbers looks like this:

def add_numbers(a, b):   result = a + b   return result

The word def tells Python you are defining a function. add_numbers is the name. a and b are the parameters — the two numbers you want to add. The indented lines are the body. The return statement sends the answer back to whoever called the function.

In JavaScript, the same function looks different but works the same way:

function addNumbers(a, b) {   let result = a + b;   return result; }

JavaScript uses the word function instead of def, curly braces instead of indentation, and a semicolon at the end of each line. The logic is identical.

How to call a function and use its result

Once you have defined a function, you call it by writing its name followed by parentheses with the inputs inside. If the function returns a value, you can store that value in a variable or use it directly.

In Python:

answer = add_numbers(5, 3) print(answer) # prints 8

In JavaScript:

let answer = addNumbers(5, 3); console.log(answer); // prints 8

You can call the same function as many times as you need. Each time, you pass in different inputs and get back a different result. This is why functions save you time — you write the logic once and use it everywhere.

Functions with no parameters or no return value

Not every function needs inputs or outputs. Some functions just do something — like printing a message or updating a file — without needing information from you or sending anything back.

A function with no parameters:

def greet():   print("Hello, world!")

You call it the same way, with empty parentheses:

greet() # prints "Hello, world!"

A function that takes input but does not return anything:

def save_to_file(filename, content):   with open(filename, 'w') as f:     f.write(content)

This function takes two inputs — a filename and the content to write — but does not return a value. It just performs an action. You call it the same way:

save_to_file("notes.txt", "Remember to buy milk")

Scope: where variables inside functions live

Scope means where a variable exists and can be used. Variables created inside a function only exist inside that function. Once the function finishes running, those variables disappear.

In this Python example:

def calculate():   x = 10   y = 20   return x + y result = calculate() print(x) # Error: x does not exist here

The variable x only exists inside the calculate function. Once the function returns, x is gone. If you try to use x outside the function, you get an error. This is actually a good thing — it keeps your variables organized and prevents accidents.

Variables created outside a function (called global variables) can usually be read inside a function, but changing them inside a function is tricky and often a bad idea. Most of the time, you should pass information into a function as parameters and get information back through a return value, rather than relying on global variables.

Common patterns: loops and conditionals inside functions

Functions often contain loops and if-statements. The logic is the same as anywhere else in your code — you just put it inside the function body.

A function that finds the largest number in a list:

def find_max(numbers):   max_value = numbers[0]   for num in numbers:     if num > max_value:       max_value = num   return max_value largest = find_max([3, 7, 2, 9, 1]) print(largest) # prints 9

A function that checks whether a password is strong:

def is_strong_password(password):   if len(password) < 8:     return False   if not any(char.isdigit() for char in password):     return False   return True if is_strong_password("MyPass123"):   print("Password accepted")

These patterns work the same way inside a function as they do in the main body of your program. The difference is that the function can be called from anywhere, and the loop or conditional only runs when you call it.

Frequently Asked Questions

Can a function call another function?

Yes. One function can call another function inside its body. This is common and useful. For example, a function that processes an order might call a function to calculate tax, another to calculate shipping, and another to send a confirmation email. Breaking the work into smaller functions makes the code easier to understand and test.

What is the difference between a parameter and an argument?

A parameter is the variable name in the function definition — it is a placeholder. An argument is the actual value you pass in when you call the function. In def add_numbers(a, b):, a and b are parameters. When you call add_numbers(5, 3), the numbers 5 and 3 are arguments.

Can a function return more than one value?

Yes, though the method depends on your language. In Python, you can return multiple values separated by commas: return x, y, z. The caller receives them as a tuple and can unpack them: a, b, c = my_function(). In JavaScript, you typically return an object or array containing multiple values.

What happens if I do not return anything from a function?

The function still runs and does its job, but it returns a special "nothing" value. In Python, that is None. In JavaScript, it is undefined. If you try to use that return value, you will get unexpected behavior. If a function is not supposed to return anything, that is fine — just do not try to store or use its return value.

How do I know when to split code into a function?

If you write the same code twice, move it into a function. If a block of code does one clear job and is more than a few lines long, consider making it a function. If you need to test a piece of logic separately, put it in a function. The goal is to make your code readable and reusable, not to create a function for every single line.