Skip to content
Related Articles

Related Articles

Improve Article
Math.js compile() Function
  • Last Updated : 12 Jan, 2021

Math.js is an extensive library with mathematical functions that works on JavaScript and Node.js. The additional feature of this library is that it provides a flexible expression parser which supports symbolic computation. It is quite powerful and easy to use since it comes with many built-in functions and offers data types such as fractions, complex numbers, matrices and units.

Math.js Compile function is used for parsing and compiling an expression. The Math.js Compile function returns an object with the compiled expression which is of the function Math.js evaluate([scope]). 

Syntax:

math.compile(expression)     
or                  
math.compile([expression A, expression B, expression C, ...])

Parameters: This method accepts only one parameter which is mentioned and described below:

  • Expression: This parameter is used to specify the expression which has to be compiled.

Return Value: This method returns an object with the compiled expression.



Example 1:

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <!-- specifying the Mathjs source -->
    <script type="text/javascript" 
        src="math.js">
    </script>
</head>
  
<body>
    <script type="text/javascript">
  
        // Defining a constant and calling
        // the compile function
        const a = math.compile('pow(4, 3)')
  
        // Displaying the output
        document.writeln(" Result = " 
                + a.evaluate());
    </script>
</body>
  
</html>

Output:

Result = 64

Example 2:

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <!-- specifying the Mathjs source -->
    <script type="text/javascript" 
        src="math.js">
    </script>
</head>
  
<body>
    <script type="text/javascript">
  
        // Defining a scope
        let testScope = { a: 30, b: 5 }
  
        // Calling the compile function
        const result = math.compile('a/b')
  
        // Displaying the result
        document.writeln(" Result = "
            + result.evaluate(testScope));
    </script>
</body>
  
</html>

Output:

Result = 6

Example 3:

HTML




<!DOCTYPE HTML>
<html>
  
<head>
  
    <!-- specifying the Mathjs source -->
    <script type="text/javascript" 
        src="math.js">
    </script>
</head>
  
<body>
    <script type="text/javascript">
  
        // Defining a node and calling 
        // the compile function
        const testNode = math.compile(
            ['a = 12', 'b = 2', 'a / b'])
  
        // Displaying the result
        document.writeln(" Result = " 
            + testNode[2].evaluate());
    </script>
</body>
  
</html>

Output:

Result = 6

Note: This will not work in normal JavaScript because it requires the Math.js library to be installed.




My Personal Notes arrow_drop_up
Recommended Articles
Page :