As of 2011, the latest version of the language is JavaScript 1.8.5. It is a superset of ECMAScript (ECMA-262) Edition 3. Extensions to the language, including partial ECMA Script for XML (E4X) (ECMA-357) support and experimental features considered for inclusion into future ECMAScript editions, are documented here.
Simple Examples.
Variables in JavaScript can be defined using the
var
keyword:var x; // defines the variable x, although no value is assigned to it by default var y = 2; // defines the variable y and assigns the value of 2 to it
Note the comments in the example above, both of which were preceded with two forward slashes.
There is no built-in I/O functionality in JavaScript; the run time environment provides that. The ECMAScript specification in edition 5.1 mentions:
However, most run time environments have a
console
object that can be used to print output. Here is a minimalist Hello World program:console.log("Hello world!");
A simple recursive function:
function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); }
Anonymous function (or lambda) syntax and closure example:
var displayClosure = function() { var count = 0; return function () { return ++count; }; } var inc = displayClosure(); inc(); // returns 1 inc(); // returns 2 inc(); // returns 3
Variadic function demonstration (arguments is a special variable).
var sum = function() { var i, x = 0; for (i = 0; i < arguments.length; ++i) { x += arguments[i]; } return x; } sum(1, 2, 3); // returns 6
Immediately-invoked function expressions allow functions to pass around variables under their own closures.
var v; v = 1; var getValue = (function(v) { return function() {return v;}; })(v); v = 2; getValue(); // 1
More Advanced Example.
This sample code displays various JavaScript features.
/* Finds the lowest common multiple (LCM) of two numbers */ function LCMCalculator(x, y) { // constructor function var checkInt = function (x) { // inner function if (x % 1 !== 0) { throw new TypeError(x + " is not an integer"); // throw an exception } return x; }; this.a = checkInt(x) // semicolons ^^^^ are optional, a newline is enough this.b = checkInt(y); } // The prototype of object instances created by a constructor is // that constructor's "prototype" property. LCMCalculator.prototype = { // object literal constructor: LCMCalculator, // when reassigning a prototype, set the constructor property appropriately gcd: function () { // method that calculates the greatest common divisor // Euclidean algorithm: var a = Math.abs(this.a), b = Math.abs(this.b), t; if (a < b) { // swap variables t = b; b = a; a = t; } while (b !== 0) { t = b; b = a % b; a = t; } // Only need to calculate GCD once, so "redefine" this method. // (Actually not redefinition—it's defined on the instance itself, // so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd. // Note that this leads to a wrong result if the LCMCalculator object members "a" and/or "b" are altered afterwards.) // Also, 'gcd' === "gcd", this['gcd'] === this.gcd this['gcd'] = function () { return a; }; return a; }, // Object property names can be specified by strings delimited by double (") or single (') quotes. lcm : function () { // Variable names don't collide with object properties, e.g., |lcm| is not |this.lcm|. // not using |this.a * this.b| to avoid FP precision issues var lcm = this.a / this.gcd() * this.b; // Only need to calculate lcm once, so "redefine" this method. this.lcm = function () { return lcm; }; return lcm; }, toString: function () { return "LCMCalculator: a = " + this.a + ", b = " + this.b; } }; // Define generic output function; this implementation only works for web browsers function output(x) { document.body.appendChild(document.createTextNode(x)); document.body.appendChild(document.createElement('br')); } // Note: Array's map() and forEach() are defined in JavaScript 1.6. // They are used here to demonstrate JavaScript's inherent functional nature. [[25, 55], [21, 56], [22, 58], [28, 56]].map(function (pair) { // array literal + mapping function return new LCMCalculator(pair[0], pair[1]); }).sort(function (a, b) { // sort with this comparative function return a.lcm() - b.lcm(); }).forEach(function (obj) { output(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm()); });
The following output should be displayed in the browser window.
LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56 LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168 LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275 LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638
Use In Web Pages.
The most common use of JavaScript is to add client-side behavior to HTML pages, a.k.a. Dynamic HTML (DHTML). Scripts are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are:
- Loading new page content or submitting data to the server via AJAX without reloading the page (for example, a social network might allow the user to post status updates without leaving the page)
- Animation of page elements, fading them in and out, re sizing them, moving them, etc.
- Interactive content, for example games, and playing audio and video
- Validating input values of a web form to make sure that they are acceptable before being submitted to the server.
- Transmitting information about the user's reading habits and browsing activities to various websites. Web pages frequently do this for web analytics, ad tracking, personalization or other purposes.
Because JavaScript code can run locally in a user's browser (rather than on a remote server), the browser can respond to user actions quickly, making an application more responsive. Furthermore, JavaScript code can detect user actions which HTML alone cannot, such as individual keystrokes. Applications such as Gmail take advantage of this: much of the user-interface logic is written in JavaScript, and JavaScript dispatches requests for information (such as the content of an e-mail message) to the server. The wider trend of Ajax programming similarly exploits this strength. A JavaScript engine (also known as JavaScript interpreter or JavaScript implementation) is an interpreter that interprets JavaScript source code and executes the script accordingly. The first JavaScript engine was created by Brendan Eich at Netscape Communications Corporation, for the Netscape Navigator web browser. The engine, code-named Spider Monkey, is implemented in C. It has since been updated (in JavaScript 1.5) to conform to ECMA-262 Edition 3. The Rhino engine, created primarily by Norris Boyd (formerly of Netscape; now at Google) is a JavaScript implementation in Java. Rhino, like Spider Monkey, is ECMA-262 Edition 3 compliant.
A web browser is by far the most common host environment for JavaScript. Web browsers typically create "host objects" to represent the Document Object Model (DOM) in JavaScript. The web server is another common host environment. A JavaScript web server would typically expose host objects representing HTTP request and response objects, which a JavaScript program could then interrogate and manipulate to dynamically generate web pages.
Because JavaScript is the only language that the most popular browsers share support for, it has become a target language for many frameworks in other languages, even though JavaScript was never intended to be such a language. Despite the performance limitations inherent to its dynamic nature, the increasing speed of JavaScript engines has made the language a surprisingly feasible compilation target.
Example Script.
Below is a minimal example of a standards-conforming web page containing JavaScript (using HTML 5 syntax) and the DOM:
<!DOCTYPE html> <meta charset="utf-8"> <title>Minimal Example</title> <h1 id="header">This is JavaScript</h1> <script> document.body.appendChild(document.createTextNode('Hello World!')); var h1 = document.getElementById('header'); // holds a reference to the <h1> tag h1 = document.getElementsByTagName('h1')[0]; // accessing the same <h1> element </script> <noscript>Your browser either does not support JavaScript, or has it turned off.</noscript>
Compatibility Considerations.
Because JavaScript runs in widely varying environments, an important part of testing and debugging is to test and verify that the JavaScript works across multiple browsers.
The DOM interfaces for manipulating web pages are not part of the ECMAScript standard, or of JavaScript itself. Officially, the DOM interfaces are defined by a separate standardization effort by the W3C; in practice, browser implementations differ from the standards and from each other, and not all browsers execute JavaScript.
To deal with these differences, JavaScript authors can attempt to write standards-compliant code which will also be executed correctly by most browsers; failing that, they can write code that checks for the presence of certain browser features and behaves differently if they are not available. In some cases, two browsers may both implement a feature but with different behavior, and authors may find it practical to detect what browser is running and change their script's behavior to match. Programmers may also use libraries or tool kits which take browser differences into account.
Furthermore, scripts may not work for some users. For example, a user may:
- use an old or rare browser with incomplete or unusual DOM support,
- use a PDA or mobile phone browser which cannot execute JavaScript,
- have JavaScript execution disabled as a security precaution,
- use a speech browser due to, for example, a visual disability.
To support these users, web authors can try to create pages which degrade gracefully on user agents (browsers) which do not support the page's JavaScript. In particular, the page should remain usable albeit without the extra features that the JavaScript would have added. An alternative approach that many find preferable is to first author content using basic technologies that work in all browsers, then enhance the content for users that have JavaScript enabled. This is known as progressive enhancement.
Accessibility.
Assuming that the user has not disabled its execution, client-side web JavaScript should be written to enhance the experiences of visitors with visual or physical disabilities, and certainly should avoid denying information to these visitors. Screen readers, used by the blind and partially sighted, can be JavaScript-aware and so may access and read the page DOM after the script has altered it. The HTML should be as concise, navigable and semantically rich as possible whether the scripts have run or not. JavaScript should not be totally reliant on mouse or keyboard specific events because a user may be physically unable to use these input devices. For this reason, device-agnostic events such as
onfocus
and onchange
are preferable to device-centric events such asonmouseover
and onkeypress
in most cases. JavaScript should not be used in a way that is confusing or disorienting to any web user. For example, using script to alter or disable the normal functionality of the browser, such as by changing the way the "back" or "refresh" buttons work, is usually best avoided. Equally, triggering events that the user may not be aware of reduces the user's sense of control as do unexpected scripted changes to the page content. Often the process of making a complex web page as accessible as possible becomes a nontrivial problem where issues become matters of debate and opinion, and where compromises are necessary in the end. However, user agents and assistive technologies are constantly evolving and new guidelines and relevant information are continually being published on the web. Security.
JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-related actions, not general-purpose programming tasks like creating files. Second, scripts are constrained by the same origin policy: scripts from one web site do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox.
There are subsets of general JavaScript — ADsafe, Secure ECMA Script (SES) — that provide greater level of security, especially on code created by third parties (such as advertisements).
Content Security Policy is the main intended method of ensuring that only trusted code is executed on a web page.