Function parse #
Parse an expression. Returns a node tree, which can be evaluated by
invoking node.evaluate() or transformed into a functional object via node.compile().
Note the evaluating arbitrary expressions may involve security risks,
see https://mathjs.org/docs/expressions/security.html for more information.
Syntax #
math.parse(expr)
math.parse(expr, options)
math.parse([expr1, expr2, expr3, ...])
math.parse([expr1, expr2, expr3, ...], options)
Parameters #
| Parameter |
Type |
Description |
expr |
string | string[] | Matrix |
Expression to be parsed |
options |
{nodes: Object<string, Node>} |
Available options:</br>- nodes a set of custom nodes |
Returns #
| Type |
Description |
| Node | Node[] |
node |
Throws #
Examples #
const node1 = math.parse('sqrt(3^2 + 4^2)')
node1.compile().evaluate() // 5
let scope = {a:3, b:4}
const node2 = math.parse('a * b')
node2.evaluate(scope) // 12
const code2 = node2.compile()
code2.evaluate(scope) // 12
scope.a = 5
code2.evaluate(scope) // 20
const nodes = math.parse(['a = 3', 'b = 4', 'a * b'])
nodes[2].compile().evaluate() // 12
See also #
evaluate,
compile
History #
| Version |
Comment |
| v0.9 |
Created |
| v0.13 |
Switched to one-based indices |
| v0.14 |
Added [1,2;3,4] notation for matrices |
| v0.18 |
Dropped the function keyword |
| v0.20 |
Added ternary conditional |
| v0.27 |
Allow multi-line expressions; allow functions that receive unevaluated parameters (rawArgs) |
| v3 |
Add object notation; allow assignments internal to other expressions |
| v7.3 |
Supported binary, octal, and hexadecimal notation |
| v9.5 |
Support for calculations with percentages |
| v12.4 |
Allow trailing commas in matrices |
| v14.8 |
Add nullish coalescing operator |
| v15.1 |
Add optional chaining operator |