---
title: Macros
project: Total.js V4
version: 0.0.99
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/macros/
updated: 2026-11-16T15:41:10.817Z
---

# Macros

> Compile a small rule language into a function with NEWMACRO(), for rules that users write.

`NEWMACRO(str, [nocompile], [isasync])` compiles a small rule language into a function. It is useful when users write rules in your application (prices, discounts, validations) and you do not want to run their JavaScript.

```js
var macro = NEWMACRO([
	'// discount rule',
	'IF total > 1000 AND vip',
	'	RETURN discount(total, 15)',
	'ELSE IF total > 500',
	'	RETURN discount(total, 5)',
	'FI',
	'RETURN total'
].join('\n'));

var helpers = {};
helpers.discount = function(value, percentage) {
	return value - (value / 100 * percentage);
};

macro({ total: 1200, vip: true }, helpers); // 1020
```

The language has `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, the values `TRUE`, `FALSE`, `YES`, `NO`, `OK` and `NULL`, quoted values, comments with `//` and private variables with `#`:

```js
var macro = NEWMACRO('#price = price * count\nIF #price > 100\nRETURN "big"\nFI\nRETURN "small"');
```

Names are converted to lower case, so properties of the model and names of helpers must be lower case. Avoid property names that contain the words `if` or `else`, because the compiler replaces them as keywords. With `isasync` the helpers can be async functions and the macro returns a Promise. With `nocompile` you get the generated JavaScript, which helps when you debug a rule.
