PROGRAMMING-CONCEPTS

Function: Definition, Syntax, and Examples

A function is a reusable block of code that performs a specific task. It allows you to group related operations together, give them a name, and reuse them as often as needed.

In programming, when you ask what is a function, imagine it as a small machine: you send in information (input), it performs a process, and it gives back a result (output).


How Functions Work

A function is defined once and can be executed many times. Most functions take parameters—values that change each time you call them—and may return a result using a return statement.

For example, a function that calculates the total cost:

def total(price, tax):
    return price + (price * tax)

Calling it like total(100, 0.2) returns 120.

Functions make code cleaner, modular, and easier to maintain.


Function Syntax in Different Languages

Although each programming language has different syntax, the structure is similar: define → call → return.

Python

def square(number):
    return number * number

def defines the function, followed by its name, parameters, and body.


JavaScript / TypeScript

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

JavaScript and TypeScript use the function keyword. TypeScript can add type safety:

function square(number: number): number {
  return number * number;
}

Swift

func square(_ number: Int) -> Int {
    return number * number
}

Swift syntax declares both input and output types explicitly, reducing runtime errors.


SQL

SQL includes both built-in and user-defined functions.

SELECT ROUND(price, 2) AS formatted_price FROM products

Here, ROUND() is a function that rounds a number to two decimal places.


Why Functions Matter

Functions help you avoid repetition and organize your logic into meaningful sections. Without them, every action would have to be written manually.

They’re essential for:

  • Reusability: Define logic once, use it in multiple places.
  • Abstraction: Hide details so code is easier to understand.
  • Testing: Smaller functions are easier to isolate and verify.

Functions in Real Applications

Functions appear everywhere—from data processing to user interaction.

React (JavaScript)

In React, functions define UI components:

function Button({ label }) {
  return <button>{label}</button>;
}

This function takes a label as input and returns JSX (HTML-like code). It demonstrates that functions don’t just calculate values—they can render interfaces.

React also uses anonymous functions for event handling:

<button onClick={() => alert("Clicked!")}>Click me</button>

This inline function executes only when triggered by user interaction.


Built-In and User-Defined Functions

All languages come with built-in functions—predefined blocks that simplify common tasks.

Examples include:

  • Python: len(), print(), sum()
  • JavaScript: parseInt(), Math.max(), setTimeout()
  • SQL: COUNT(), AVG(), LOWER()
  • Swift: print(), abs(), max()

You can combine these with your own custom functions to extend what the language can do.


Higher-Order and Anonymous Functions

Some languages treat functions as values—you can pass them as arguments or return them from other functions. These are higher-order functions.

JavaScript example:

function applyTwice(fn, value) {
  return fn(fn(value));
}

function addOne(x) {
  return x + 1;
}

console.log(applyTwice(addOne, 5)); // Output: 7

Here, applyTwice accepts another function as input.

Anonymous functions, often used with array methods, don’t have names:

[1, 2, 3].map(x => x * 2);

This pattern makes code concise and expressive.


Common Function Mistakes

Beginners often trip over the same issues when defining or calling functions:

  • Forgetting parentheses when calling: Writing add instead of add().
  • Incorrect parameter counts: Passing too many or too few arguments.
  • No return value: Omitting return when one is needed.
  • Variable scope confusion: Using variables from outside the function unintentionally.
  • Mismatched types: Especially common in Swift and TypeScript.

Understanding these helps prevent subtle bugs and improves readability.


Functions in SQL and CSS Contexts

While CSS doesn’t use functions the same way as programming languages, it includes functional notation that follows similar syntax principles.

Example:

background-color: rgb(0, 122, 255);
transform: rotate(45deg);

Each parenthesized expression behaves like a function—it takes parameters and returns a result.

In SQL, functions structure database logic. They can compute values, format data, or filter results.

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;

CONCAT() combines columns into one value, mirroring how programming functions process input to produce output.


Best Practices for Writing Functions

  • Keep them short. A function should do one thing well.
  • Name them clearly. Use verbs like calculateTotal() or validateEmail().
  • Avoid side effects. Functions should return predictable results.
  • Reuse wisely. If two parts of your code do the same thing, extract that logic into a shared function.
  • Document intent. Use comments or docstrings to explain why the function exists, not just what it does.

Well-written functions make your codebase scalable and easier for others to understand.


Summary

A function is a cornerstone of computer programming—a named set of instructions that performs a specific task and often returns a result.

Learning how functions work helps you structure programs into logical, reusable pieces. From Python’s def and JavaScript’s function to SQL’s COUNT() and Swift’s func, every language depends on this concept.

Once you grasp functions, you understand how programs organize behavior, communicate results, and stay efficient as they grow.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster