Javascript (ECMAScript)

Examples

Lights out game.

Minesweep game.

Monte Carlo compute of π (HTML5).

Quick reference

String

Array

Mathematics

Date

Tricks

String to double or int

Integer division

17/5 yields 3.4, to get an integer, we can append an bitwise operation to force the result as an integer, like (17/5) | 0, or (17/5) >> 0.

Strip/trim spaces

To remove leading and trailing spaces: function trim(s) { return s.replace('/^\s+|\s+$/g', ''); } or to remove all spaces s.replace('/\s+/g', '').

Evaluate expression eval(s)

eval("1+2") returns 3, eval("document.write('abc')") writes "abc".

Extensions

Javascript can be extended through some helper scripts (Javascript frameworks), such as jQuery, MooTools, and Prototype. Click here for a list from wikipedia.

Debug tools

The web browser Mozilla Firefox has a web developer console (Web developer/Web Console in version 6), which can output useful error messages.

The web browser Chrome has a more useful tool to visually debug a webpage. Click the configure button next to the address bar, choose Tools/Developer Tools (Shift+Ctrl+I) and/or Tools/Javascript Console(Shift+Ctrl+J).

Internet Explorer 9 and later also has a good developer tool. Start debugging will start the Javascript debugger.

The web browser Opera (free to use) has a more useful tool to visually debug a webpage. In a page, right click to show the pop-up menu, click Inspect Element. A debug window will show up.

Online tutorials

  1. W3School Javascript is probably the best place to learn Javascript online.
  2. Java2s gives many useful examples.
  3. Javascript Events
  4. Dive into HTML5

Specifications

There are two parts of Javascript Language: 1. the language itself. 2. interaction with HTML elements (called document object model, dom DOM).

The language itself is specified in ECMA website.

DOM standard is in W3C. A zip for the most commonly used DOM2 is here.