Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

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:

javascript:7*45
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():
        javascript:alert(7*45)
    
  • Creating a keyword: Go to “Preferences → Basics → Search → Manage Search Engines...” and create a new entry with the following URL:
        javascript:alert(%s)
    
JavaScript you can use:
  • Arithmetic operators: addition (+), subtraction (-), multiplication (*), and division (/), modulo (%).
        > 77 / 11
        7
        > 3.16 * 5
        15.8
        > 10 % 7
        3
    
  • 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)
        'ff'
        > parseInt("ff", 16)
        255
    
    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

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}