Version: 0.28.0

Constants & Variables

The next building block after types are constants and variables.

Constants#

Constants are immutable by design, which means their values cannot be reassigned. Put in another way, they can be assigned once, at their declaration. When defining a constant you need to provide a name, type and a value:

Constants in JsLIGO are enforced:

let x = (a: int): int => {
const age : int = 25;
age = 3; // gives an error
};

Unlike the other syntaxes, JsLIGO doesn't allow variable names to be reused in the same block scope:

let x = (a: int): int => {
const age: int = 25;
const age: int = 3; // will give an error
};

However, the following does work:

let x = (a: int): int => {
const age: int = 25;
{
const age: int = 3; // does not give an error
return age;
}
};

You can evaluate the constant definition above using the following CLI command:

ligo run evaluate-expr gitlab-pages/docs/language-basics/src/variables-and-constants/const.jsligo --entry-point age
# Outputs: 25

Variables#

Variables, unlike constants, are mutable.

⚠️ Please be wary that mutation only works within the function scope itself, values outside of the function scope will not be affected. In other words, when a function is called, its arguments are copied, as well as the environment. Any side-effect to that environment is therefore lost when the function returns.

let add = (a: int, b: int): int => {
let c = a;
c = c + b;
return c
}

You can run the add function defined above using the LIGO compiler like this:

ligo run evaluate-call gitlab-pages/docs/language-basics/src/variables-and-constants/add.jsligo '(1,1)' --entry-point add
# Outputs: 2