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

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}