Skip to content

Math.js: User-Defined Functions

JS Calc allows you to define your own custom functions using a straightforward syntax, similar to how you might define them in traditional programming or mathematical notation. These functions are powered by Math.js and can significantly streamline repetitive calculations or encapsulate complex formulas.

Defining Functions

The syntax for defining a function is: functionName(param1, param2, ...) = expression

  • functionName: The name you want to give your function.
  • param1, param2, ...: Comma-separated parameter names that your function will accept as input.
  • expression: The mathematical expression that defines what your function does. This expression can use the defined parameters, other variables, built-in functions, and even other user-defined functions.

Examples:

  1. A simple squaring function:
> f(x) = x^2

(Defining a function does not produce an output line itself and does not update the @ variable.)

  1. Area of a circle:
> circleArea(radius) = pi * radius^2
  1. Hypotenuse of a right triangle:
> hypot(a, b) = sqrt(a^2 + b^2)
  1. A function with multiple parameters and operations:
> calculateY(m, x, c) = m*x + c

Using Functions

Once a function is defined, you can call it by its name, providing the required arguments in parentheses:

> f(x) = x^2 // Define
> f(5) // Use
 25

> circleArea(radius) = pi * radius^2 // Define
> r = 10 // Define
> circleArea(r) // Use
 314.15926535898
> circleArea(5) // Use
 78.539816339745

> hypot(a, b) = sqrt(a^2 + b^2)
> hypot(3, 4)
 5
> hypot(10, 17)
 19.723082923316

> calculateY(m, x, c) = m*x + c
> calculateY(3, 4, 7)
 19

Functions can also be used within other expressions:

> g(y) = 2y + 1
> h(z) = z^3
> g(h(2)) // g(2^3) => g(8)
 17

Persistence

User-defined functions are automatically saved when you define them. They will be available when you close and reopen the calculator, persisting between sessions until you explicitly clear the calculator's state using the Clear link.

Overwriting and Clearing

  • If you define a function with the same name as an existing function (either built-in or user-defined), the new definition will overwrite the old one for subsequent calculations within that session (and will be saved as such).
  • Using the Clear link will remove all user-defined functions along with variables and history.