Skip to main content
Version: 1.3.0

Declaring

LIGO functions are the basic building block of contracts.

The semantics of function calls in LIGO is that of a copy of the arguments but also of the environment. This means that any mutation (assignment) on variables outside the scope of the function will be lost when the function returns, just as the mutations inside the functions will be.

Function declarations can be introduced in two main ways: either by the keyword function or the keyword const (the keyword let is possible too, but defaulted to const in this instance). The latter manner is preferred when the function body is an expression. For example, here is how you define a basic function that sums two integers:

const add = (x,y) => x + y; // Single-expression body
const int_add = (x: int, y: int) : int => x + y

This means that add is a function that takes a pair of integers and returns their sum.

If the body contains statements instead of a single expression, you would use a block and a return statement:

const double_sum = (x: int, y: int) : int => {
const doubleX = 2*x;
const doubleY = 2*y;
return doubleX + doubleY;
};

although it is arguably more readable to use function, like so:

function double_sum_bis (x: int, y: int) {
const doubleX = 2*x;
const doubleY = 2*y;
return doubleX + doubleY;
};

Note that JsLIGO, like JavaScript, requires the return keyword to indicate what is being returned. If return is not used, it will be the same as return [] (unit).

By default, LIGO will warn about unused arguments inside functions. In case we do not use an argument, its name should start with _ to prevent warnings.

const drop = (x, _y) => x; // _y silently ignored

Functions can capture variables in their bodies that are defined outside:

const double_incr = x => add (x,x) + 1; // add is captured from outside

We could have the same phenomenon with nested functions instead of two functions at the same scope level:

function convoluted_doubling (x) {
const addX = y => x + y; // x is bound by convoluted_doubling
return addX(x);
}