freeCodeCamp/guide/english/mathematics/what-is-a-function/index.md

1.1 KiB

title
What Is a Function

What Is a Function

A function is mathematically defined as a mapping of one set of numbers to another. For example f(x) = x*2. Any given input from some set (called the domain) always gives one specific output from the range. In the doubling function the inputs 1,3,and 5 map to the numbers 2,6, and 10 in the range, which is also the set of all real numbers.

In contrast, a "function" in programming (more accurately called a method or subroutine in some languages) is a method that takes one or more values and outputs one or more outputs. There is generally no guarantee that some internal state (such as a global variable) could change in such a way that f(2) could be 5 at one time, or 10 when you run it again. In most languages that is permitted, even expected in some cases, but some languages using functional programming define functions as functions mathematically in that there are no state variables that can change and have inconsistencies, thereby giving more "provably correct" code.

More Information:

Functional languages: Haskell, Clojure