Over a million developers have joined DZone.

Tip: use JavaScript as a calculator in Firefox and Chrome

DZone's Guide to

Tip: use JavaScript as a calculator in Firefox and Chrome

· Web Dev Zone ·
Free Resource

Have you seen our HERE Twitch channel to livestream our Developer Waypoints series?

The following tip allows you to quickly perform calculations via JavaScript in Firefox and Chrome.

Basic idea: If you enter a javascript: URL in Firefox, the result of the expression is shown in the window. For example, try the following URL:

Firefox: By using a keyword [1], you can save 8 keystrokes (9 if your keyword is j instead of js). Just create the following bookmark:
  • Name: Compute with JavaScript
  • Location: javascript:%s
  • Keyword: js
Now you can perform the above calculation by typing
    js 7*45

Google Chrome: handles output and keywords differently than Firefox.

  • JavaScript code to display a result: As Webkit browsers don’t replace the page content with the result of a JavaScript expression, you need to explicitly display the result, e.g. via alert():
  • Creating a keyword: Go to “Preferences → Basics → Search → Manage Search Engines...” and create a new entry with the following URL:
JavaScript you can use:
  • Arithmetic operators: addition (+), subtraction (-), multiplication (*), and division (/), modulo (%).
        > 77 / 11
        > 3.16 * 5
        > 10 % 7
  • Properties and methods of the global Math object [2]:
    • Math.PI
    • Math.pow(base, exponent)
    • Math.sqrt(x)
    • Math.sin(x)
  • Converting to and from hexadecimal, binary, etc.
        > (255).toString(16)
        > parseInt("ff", 16)
    You need to put the number in parenthesis to invoke a method on it. Otherwise the dot will be mistaken as a decimal point. Alternatively, you can type two dots or append .0 to the number.


From http://www.2ality.com/2011/06/javascript-calculator.html

Developer Waypoints is a live coding series from HERE, which will teach you how to build with maps and location data.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}