Previous Page
Next Page

A Bookmarklet Calculator

If you think about it, it's really a bit too difficult to do a full-fledged calculator with buttons and a running value on just one long line of code. However, you can use a bookmarklet like Script 17.12 to do fairly complex calculations, using JavaScript's built-in Math functions, as described in Table 17.1.

Script 17.12. Surprisingly complex equations can be evaluated with this bookmarklet.

javascript:var evl,em,expr=prompt('Formula... (eg: 2*3 + 7/8)','');with(Math)try{evl= 
parseFloat(eval(expr));if(isNaN(evl)) {throw Error('Not a number!');}void(prompt ('Result:'

Table 17.1. JavaScript's Math Functionality




Absolute value

sin, cos, tan

Standard trigonometric functions; arguments in radians

acos, asin, atan

Inverse trigonometric functions; return values in radians

exp, log

Exponential and natural logarithm, base e


Returns least integer greater than or equal to argument


Returns greatest integer less than or equal to argument


Returns lesser of two arguments


Returns greater of two arguments


Exponential; first argument is base, second is exponent


Rounds argument to nearest integer


Square root

To use a JavaScript calculator:

javascript:var evl,em,expr=prompt ('Formula...(eg: 2*3 + 7/8)','');

This line sets up two variables and then prompts the user for an expression or formula, as shown in Figure 17.22, which is stored in expr.

Figure 17.22. The user must be prompted for a formula.


The next few lines need to be evaluated using JavaScript's built-in Math routines. The with(Math) line tells the interpreter that when any of these functions are seen, to evaluate them as Math commands.

The try{} warns JavaScript that what we're doing may well fail, and if so, don't panic. In fact, don't even put up an error message if there's a problem, as we'll be handling the errors ourselves.


Evaluate the expression, and turn it into a floating-point number, which is then stored in evl.


If the resulting value in evl is not a number (NaN), do the following line.

{throw Error('Not a number!');}

If we're here, for some reason what the user entered didn't work out to a number. When that happens we want to force an error message of "Not a number!" to display. Here's where the message is set; it will be displayed in step 7.


Otherwise, the expression was valid, so display the result, as shown in Figure 17.23.

Figure 17.23. JavaScript returns the result of the calculation.


Here's the end of that try{} block that started in step 2. To get here, one of two things happened: either we ran into the error in step 5, or some other error entirely occurred. Either way, we "catch" the error that was "thrown" and put it up on the screen in an alert.


  • Trying to remember where you've seen that try/throw/catch syntax before? It was originally covered way back in the "Handling Errors" section of Chapter 3.

Previous Page
Next Page