PrimitiveType

Simple JavaScript Calculator


In this article I describe the development of my very simple JavaScript calculator page. I created the calculator page because I wanted to use the keyboard to enter the numbers and operators, and see the trail of these that I had entered before submitting them for an answer. I couldn't find a similar built-in facility for Windows (i.e. one that I wouldn't have to download and install). MS Calculator doesn't let you see the trail of numbers and operators - and although Linux has bc (which I really like), I only get to use it when I have an SSH session going with the Linux server at work. Putting my script on a web page means I can use it on any computer with a web browser and an internet connection.

I sat down to write the calculator code thinking about stacks and pushing and popping numbers and operators on and off them, something I came across in a programming book. This was gonna take some time, I thought; but in the end I used a much simpler method and the calculator was written very quickly.

In fact, most of the work for the calculator is done by JavaScript itself. JavaScript (like a lot of other programming languages) can have statements that resemble simple mathematical expressions, such as "1 + 2", which unsurprisingly evaluates to 3. I realized that if I could get JavaScript to evaluate such an expression for me, I wouldn't have to write the code to do so myself. The JavaScript function eval() does just that.

However, as users can enter anything they like in a text field, I had to be sure that what was passed to eval() was at least restricted to the characters one might use in simple arithmetic. This is achieved by comparing the input to a regular expression requiring that only certain characters be present in the string. The characters accepted are:

  • 0-9
  • .
  • +, -, *, /
  • (, )
  • [space]

Even if the characters supplied are valid, the user can still enter a non-sensical expression such as ")(", which would generate an error when passed to eval(). The solution here was to wrap the call to eval() in a try-catch statement. JavaScript attempts to evaluate the string passed to eval(), and if it encounters an error, such as a syntax error, an exception is generated and dealt with in the catch clause.

I decided that any input deemed invalid would cause my function to return the string "err", which is suitable for the purposes of my calculator page. It might be a better idea to return something else, perhaps NULL, if the function were to be used as a general purpose calculator. Note that passing an empty string to eval() returns "undefined" - I had my function return zero instead. Here is the basic function behind the calculator page (with some variables renamed and more commenting):

// Evaluates the expression passed and returns the answer.
// If the input is in some way invalid, returns 'err'.
// If the input is empty, returns zero.
function calculate(expression)
{
  var answer = 'err';// Default answer

  // expression must match the regular expression
  if (expression.match(/^[0-9+\-*/(). ]*$/))
  {
    try
    {
      // eval() attempts to evaluate expression
      // If expression is empty, assign zero to answer
      answer = expression != '' ? eval(expression) : '0';
    }
    catch (e)
    {
      // Syntax error - Do nothing... answer remains 'err'
    }
  }
  
  return answer;
}

There are other JavaScript fragments on the page that pass the user input to the function and write the return value to the answer text field. These can be seen by viewing the source of the page.