JavaScript is a prototype-based
scripting languageA scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...
that is dynamic,
weakly typedIn computer science, weak typing is a property attributed to the type systems of some programming languages. It is the opposite of strong typing, and consequently the term weak typing has as many different meanings as strong typing does.One of the more common definitions states that weakly typed...
and has first-class functions. It is a multi-paradigm language, supporting
object-orientedObject-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
,
imperativeIn computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
, and
functionalIn computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
programming styles.
JavaScript was formalized in the
ECMAScriptECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...
language standard and is primarily used in the form of
client-side JavaScriptClient-side JavaScript is JavaScript that runs on the client-side. While JavaScript was originally created to run this way, the term was coined because the language is no longer limited to just client-side, since server-side JavaScript is now available.-Environment:The most common Internet media...
, implemented as part of a
Web browserA web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...
in order to provide enhanced
user interfaceThe user interface, in the industrial design field of human–machine interaction, is the space where interaction between humans and machines occurs. The goal of interaction between a human and a machine at the user interface is effective operation and control of the machine, and feedback from the...
s and dynamic
websiteA website, also written as Web site, web site, or simply site, is a collection of related web pages containing images, videos or other digital assets. A website is hosted on at least one web server, accessible via a network such as the Internet or a private local area network through an Internet...
s. This enables
programmaticComputer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...
access to computational objects within a host environment.
JavaScript's use in
applicationsApplication software, also known as an application or an "app", is computer software designed to help the user to perform specific tasks. Examples include enterprise software, accounting software, office suites, graphics software and media players. Many application programs deal principally with...
outside Web pages — for example in
PDFPortable Document Format is an open standard for document exchange. This file format, created by Adobe Systems in 1993, is used for representing documents in a manner independent of application software, hardware, and operating systems....
documents,
site-specific browserA site-specific browser is a software application that is dedicated to accessing pages from a single source on a computer network such as the Internet or a private intranet. SSBs typically simplify the more complex functions of a web browser by excluding the menus, toolbars and browser chrome...
s, and desktop widgets — is also significant. Newer and faster JavaScript
VMsA virtual machine is a "completely isolated guest operating system installation within a normal host operating system". Modern virtual machines are implemented with either software emulation or hardware virtualization or both together.-VM Definitions:A virtual machine is a software...
and frameworks built upon them (notably
Node.jsNode.js is a software system designed for writing highly-scalable internet applications, notably web servers.Programs are written in JavaScript, using event-driven, asynchronous I/O to minimize overhead and maximize scalability....
) have also increased the popularity of JavaScript for server-side web applications.
JavaScript uses syntax influenced by that of
CC is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
. JavaScript copies many names and naming conventions from
JavaJava is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, but the two languages are otherwise unrelated and have very different semantics. The key design principles within JavaScript are taken from the Self and Scheme programming languages.
History
JavaScript was originally developed by
Brendan EichBrendan Eich is a computer programmer and creator of the JavaScript scripting language. He is the chief technology officer at the Mozilla Corporation.-Education:...
of Netscape under the name
Mocha, which was later renamed to
LiveScript, and finally to JavaScript mainly because it was more influenced by the Java programming language.
LiveScript was the official name for the language when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but it was renamed JavaScript in a joint announcement with Sun Microsystems on December 4, 1995, when it was deployed in the Netscape browser version 2.0B3.
The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its
Netscape NavigatorNetscape Navigator was a proprietary web browser that was popular in the 1990s. It was the flagship product of the Netscape Communications Corporation and the dominant web browser in terms of usage share, although by 2002 its usage had almost disappeared...
web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language.
It has also been claimed that the language's name is the result of a co-marketing deal between
NetscapeNetscape Communications is a US computer services company, best known for Netscape Navigator, its web browser. When it was an independent company, its headquarters were in Mountain View, California...
and
SunSun Microsystems, Inc. was a company that sold :computers, computer components, :computer software, and :information technology services. Sun was founded on February 24, 1982...
, in exchange for Netscape bundling Sun's Java runtime with its then-dominant browser.
JavaScript very quickly gained widespread success as a client-side scripting language for web pages. As a consequence,
MicrosoftMicrosoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...
named its implementation
JScriptJScript is a scripting language based on the ECMAScript standard that is used in Microsoft's Internet Explorer.JScript is implemented as a Windows Script engine. This means that it can be "plugged in" to any application that supports Windows Script, such as Internet Explorer, Active Server Pages,...
to avoid trademark issues. JScript added new date methods to fix the
Y2KThe Year 2000 problem was a problem for both digital and non-digital documentation and data storage situations which resulted from the practice of abbreviating a four-digit year to two digits.In computer programs, the practice of representing the year with two...
-problematic methods in JavaScript, which were based on Java's
java.util.Date class. JScript was included in
Internet ExplorerWindows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...
3.0, released in August 1996.
In November 1996, Netscape announced that it had submitted JavaScript to
Ecma InternationalEcma International is an international, private non-profit standards organization for information and communication systems. It acquired its name in 1994, when the European Computer Manufacturers Association changed its name to reflect the organization's global reach and activities...
for consideration as an industry standard, and subsequent work resulted in the standardized version named
ECMAScriptECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...
.
JavaScript has become one of the most popular programming languages on the web. Initially, however, many professional programmers denigrated the language because its target audience was web authors and other such "amateurs", among other reasons. The advent of
AjaxAjax is a group of interrelated web development methods used on the client-side to create asynchronous web applications...
returned JavaScript to the spotlight and brought more professional programming attention. The result was a proliferation of comprehensive
frameworks and libraries, improved JavaScript programming practices, and increased usage of JavaScript outside of web browsers, as seen by the proliferation of
server-side JavaScriptServer-side JavaScript refers to JavaScript that runs on the server-side. This term was coined because the language is predominantly used on the client-side, i.e. client-side JavaScript ....
platforms.
In January 2009, the
CommonJSCommonJS is a project with the goal of specifying an ecosystem for JavaScript outside the browser . The project was started by Kevin Dangoor in January 2009 and initially named ServerJS....
project was founded with the goal of specifying a common standard library mainly for JavaScript development outside the browser.
Trademark
"JavaScript" is a
trademarkA trademark, trade mark, or trade-mark is a distinctive sign or indicator used by an individual, business organization, or other legal entity to identify that the products or services to consumers with which the trademark appears originate from a unique source, and to distinguish its products or...
of
Oracle CorporationOracle Corporation is an American multinational computer technology corporation that specializes in developing and marketing hardware systems and enterprise software products – particularly database management systems...
. It is used under license for technology invented and implemented by Netscape Communications and current entities such as the
Mozilla FoundationThe Mozilla Foundation is a non-profit organization that exists to support and provide leadership for the open source Mozilla project. The organization sets the policies that govern development, operates key infrastructure and controls trademarks and other intellectual property...
.
Features
The following features are common to all conforming ECMAScript implementations, unless explicitly specified otherwise.
Imperative and structured
JavaScript supports much of the
structured programmingStructured programming is a programming paradigm aimed on improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures and for and while loops - in contrast to using simple tests and jumps such as the goto statement which could...
syntax from C (e.g.,
if statements,
while loops,
switch statements, etc.). One partial exception is scoping: C-style block-level scoping is not supported (instead, JavaScript has function-level scoping). JavaScript 1.7, however, supports block-level scoping with the
let keyword. Like C, JavaScript makes a distinction between
expressionsAn expression in a programming language is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
and
statementsIn computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...
. One syntactic difference from C is automatic semicolon insertion, in which the semicolons that terminate statements can be omitted.
Dynamic
dynamic typing: As in most scripting languages,
typesA type system associates a type with each computed value. By examining the flow of these values, a type system attempts to ensure or prove that no type errors can occur...
are associated with
valuesIn computer science, a value is an expression which cannot be evaluated any further . The members of a type are the values of that type. For example, the expression "1 + 2" is not a value as it can be reduced to the expression "3"...
, not with
variablesIn computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
. For example, a variable
x could be bound to a number, then later rebound to a
stringIn formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....
. JavaScript supports various ways to test the type of an object, including
duck typingIn computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface...
.
object based: JavaScript is almost entirely
object-basedIn general, object-based indicates that something such as a theory, language, or model is based on the concept of object.In computer science, the term object-based has two different senses:...
. JavaScript
objectsIn computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...
are
associative arrayIn computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....
s, augmented with prototypes (see below). Object property names are string keys:
obj.x = 10 and
obj['x'] = 10 are equivalent, the dot notation being
syntactic sugarSyntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express....
. Properties and their values can be added, changed, or deleted at run-time. Most properties of an object (and those on its prototype inheritance chain) can be enumerated using a
for...in loop. JavaScript has a small number of built-in objects such as
Function and
Date.
run-time evaluation: JavaScript includes an
evalIn some programming languages, eval is a function which evaluates a string as though it were an expression and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval...
function that can execute statements provided as strings at run-time.
Functional
first-class functions:
FunctionsIn computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....
are
first-classIn computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...
; they are objects themselves. As such, they have properties and methods, such as
length and
call; and they can be assigned to variables, passed as arguments,
returned by other functions, and manipulated like any other object. Any reference to a function allows it to be invoked using the
operator.
nested functions: "Inner" or "nested" functions are functions defined within another function. They are created each time the outer function is invoked. In addition to that, the
scopeIn computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...
of the outer function, including any constants, local variables and argument values, become part of the internal state of each inner function object, even after execution of the outer function concludes.
closures: JavaScript allows nested functions to be created, with the lexical scope in force at their definition, and has a
operator to invoke them now or later. This combination of code that can be executed outside the scope in which it is defined, with its own scope to use during that execution, is called a
closureIn computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
in computer science.
Prototype-based
prototypes: JavaScript uses
prototypesPrototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming...
instead of
classesIn object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
for
inheritanceIn object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
. It is possible to simulate many class-based features with prototypes in JavaScript.
functions as object constructors: Functions double as object constructors along with their typical role. Prefixing a function call with
new creates a new object and calls that function with its local
this keyword bound to that object for that invocation. The constructor's
prototype property determines the object used for the new object's internal prototype. JavaScript's built-in constructors, such as
Array, also have prototypes that can be modified.
functions as methods: Unlike many object-oriented languages, there is no distinction between a function definition and a
methodIn object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...
definition. Rather, the distinction occurs during function calling; a function can be called as a method. When a function is called as a method of an object, the function's local
this keyword is bound to that object for that invocation.
Miscellaneous
run-time environment: JavaScript typically relies on a run-time environment (e.g. in a
web browserA web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...
) to provide objects and methods by which scripts can interact with "the outside world". In fact, it relies on the environment to provide the ability to include/import scripts (e.g.
HTMLHyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....
elements). (This is not a language feature per se, but it is common in most JavaScript implementations.)
variadic functions: An indefinite number of parameters can be passed to a function. The function can access them through formal parameters and also through the local
arguments object.
array and object literals: Like many scripting languages, arrays and objects (associative arrays in other languages) can each be created with a succinct shortcut syntax. In fact, these
literalsIn computer science, a literal is a notation for representing a fixed value in source code. Almost all programming languages have notations for atomic values such as integers, floating-point numbers, strings, and booleans; some also have notations for elements of enumerated types and compound...
form the basis of the
JSONJSON , or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects...
data format.
regular expressions: JavaScript also supports
regular expressionIn computing, a regular expression provides a concise and flexible means for "matching" strings of text, such as particular characters, words, or patterns of characters. Abbreviations for "regular expression" include "regex" and "regexp"...
s in a manner similar to
PerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, which provide a concise and powerful syntax for text manipulation that is more sophisticated than the built-in string functions.
Vendor-specific extensions
JavaScript is officially managed by
Mozilla FoundationThe Mozilla Foundation is a non-profit organization that exists to support and provide leadership for the open source Mozilla project. The organization sets the policies that govern development, operates key infrastructure and controls trademarks and other intellectual property...
, and new language features are added periodically. However, only some non-Mozilla
JavaScript engineA JavaScript engine is specialized computer software which interprets and executes JavaScript . Although there are several uses for a JavaScript engine, it is most commonly used in web browsers.-History:...
s support these new features:
- property getter and setter functions (also supported by WebKit, Opera, ActionScript, and Rhino)
- conditional
catch clauses
- iterator protocol adopted from Python
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
- shallow generators
In computer science, a generator is a special routine that can be used to control the iteration behaviour of a loop. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values...
/coroutineCoroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations...
s also adopted from Python
- array comprehensions and generator expressions also adopted from Python
- proper block scope via the new
let keyword
- array and object destructuring (limited form of pattern matching
In computer science, pattern matching is the act of checking some sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact. The patterns generally have the form of either sequences or tree structures...
)
- concise function expressions (
function(args) expr)
- ECMAScript for XML (E4X), an extension that adds native XML support to ECMAScript
Syntax and semantics
, the latest version of the language is JavaScript 1.8.5. It is a superset of
ECMAScriptECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...
(ECMA-262) Edition 3. Extensions to the language, including partial
E4XECMAScript for XML is a programming language extension that adds native XML support to ECMAScript . The goal is to provide an alternative to DOM interfaces that uses a simpler syntax for accessing XML documents. It also offers a new way of making XML visible...
(ECMA-357) support and experimental features considered for inclusion into future ECMAScript editions, are documented here.
Simple examples
A simple
recursiveRecursion is the process of repeating items in a self-similar way. For instance, when the surfaces of two mirrors are exactly parallel with each other the nested images that occur are a form of infinite recursion. The term has a variety of meanings specific to a variety of disciplines ranging from...
function:
function factorial(n) {
if (n 0) {
return 1;
}
return n * factorial(n - 1);
}
Anonymous functionIn programming language theory, an anonymous function is a function defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell...
(or lambda) syntax and
closureIn computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
example:
function displayClosure {
var count = 0;
return function {
return count++;
};
}
var inc = displayClosure;
inc; // returns 0
inc; // returns 1
inc; // returns 2
Variadic functionIn computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages....
demonstration (
arguments is a special
variableIn computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
).
function sum {
var i,
x = 0;
for (i = 0; i < arguments.length; ++i) {
x += arguments[i];
}
return x;
}
sum(1, 2, 3); // returns 6
More advanced example
This sample code showcases various JavaScript features.
The following output should be displayed in the browser window.
Use in web pages
The primary use of JavaScript is to write functions that are embedded in or included from
HTMLHyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....
pages and that interact with the
Document Object ModelThe Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...
(DOM) of the page. Some simple examples of this usage are:
- Opening or popping up
Pop-up ads or pop-ups are a form of online advertising on the World Wide Web intended to attract web traffic or capture email addresses. Pop-ups are generally new web browser windows to display advertisements...
a new window with programmatic control over the size, position, and attributes of the new window (e.g. whether the menus, toolbars, etc., are visible).
- Validating
In computer science, data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called "validation rules" or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system...
input values of a web formA webform on a web page allows a user to enter data that is sent to a server for processing. Webforms resemble paper or database forms because internet users fill out the forms using checkboxes, radio buttons, or text fields...
to make sure that they are acceptable before being submitted to the server.
- Changing images as the mouse cursor moves over them
Rollover refers to a button created by a web developer or web designer, found within a web page, used to provide interactivity between the user and the page itself...
: This effect is often used to draw the user's attention to important links displayed as graphical elements.
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
GmailGmail is a free, advertising-supported email service provided by Google. Users may access Gmail as secure webmail, as well via POP3 or IMAP protocols. Gmail was launched as an invitation-only beta release on April 1, 2004 and it became available to the general public on February 7, 2007, though...
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- Mythology :* Ajax , son of Telamon, ruler of Salamis and a hero in the Trojan War, also known as "Ajax the Great"* Ajax the Lesser, son of Oileus, ruler of Locris and the leader of the Locrian contingent during the Trojan War.- People :...
similarly exploits this strength.
A
JavaScript engineA JavaScript engine is specialized computer software which interprets and executes JavaScript . Although there are several uses for a JavaScript engine, it is most commonly used in web browsers.-History:...
(also known as
JavaScript interpreter or
JavaScript implementation) is an
interpreterIn computer science, an interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language...
that interprets JavaScript
source codeIn computer science, source code is text written using the format and syntax of the programming language that it is being written in. Such a language is specially designed to facilitate the work of computer programmers, who specify the actions to be performed by a computer mostly by writing source...
and executes the
scriptA computer program is a sequence of instructions written to perform a specified task with a computer. A computer requires programs to function, typically executing the program's instructions in a central processor. The program has an executable form that the computer can use directly to execute...
accordingly. The first JavaScript engine was created by
Brendan EichBrendan Eich is a computer programmer and creator of the JavaScript scripting language. He is the chief technology officer at the Mozilla Corporation.-Education:...
at Netscape Communications Corporation, for the
Netscape NavigatorNetscape Navigator was a proprietary web browser that was popular in the 1990s. It was the flagship product of the Netscape Communications Corporation and the dominant web browser in terms of usage share, although by 2002 its usage had almost disappeared...
web browserA web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...
. The engine, code-named SpiderMonkey, is implemented in
CC is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
. It has since been updated (in JavaScript 1.5) to conform to ECMA-262 Edition 3. The
RhinoRhino is an open source JavaScript engine. It is developed entirely in Java and managed by the Mozilla Foundation. The Foundation also provides another implementation of JavaScript engine written in C known as SpiderMonkey....
engine, created primarily by Norris Boyd (formerly of Netscape; now at Google) is a JavaScript implementation in
JavaJava is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
. Rhino, like SpiderMonkey, is ECMA-262 Edition 3 compliant.
A web browser is by far the most common host environment for JavaScript. Web browsers typically use the public
APIAn application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...
to create "host objects" responsible for reflecting the
DOMThe Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...
into JavaScript. The
web serverWeb server can refer to either the hardware or the software that helps to deliver content that can be accessed through the Internet....
is another common application of the engine. A
JavaScript webserverServer-side JavaScript refers to JavaScript that runs on the server-side. This term was coined because the language is predominantly used on the client-side, i.e. client-side JavaScript ....
would expose host objects representing an HTTP request and response objects, which a JavaScript program could then 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 - use in web pages
A minimal example of a standards-conforming web page containing JavaScript (using
HTML 4.01HyperText Markup Language is the predominant markup language for web pages. HTML elements are the basic building-blocks of webpages....
syntax) would be the following:
"http://www.w3.org/TR/html4/strict.dtd">
simple page
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
DOMThe Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...
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
W3CThe World Wide Web Consortium is the main international standards organization for the World Wide Web .Founded and headed by Tim Berners-Lee, the consortium is made up of member organizations which maintain full-time staff for the purpose of working together in the development of standards for the...
; 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 toolkits 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
A personal digital assistant , also known as a palmtop computer, or personal data assistant, is a mobile device that functions as a personal information manager. Current PDAs often have the ability to connect to the Internet...
or mobile phoneA mobile phone is a device which can make and receive telephone calls over a radio link whilst moving around a wide geographic area. It does so by connecting to a cellular network provided by a mobile network operator...
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 gracefullyFault-tolerance or graceful degradation is the property that enables a system to continue operating properly in the event of the failure of some of its components. A newer approach is progressive enhancement...
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 enhancementProgressive enhancement is a strategy for web design that emphasizes accessibility, semantic HTML markup, and external stylesheet and scripting technologies...
.
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
disabilitiesA disability may be physical, cognitive, mental, sensory, emotional, developmental or some combination of these.Many people would rather be referred to as a person with a disability instead of handicapped...
, and certainly should avoid denying information to these visitors.
Screen readerA screen reader is a software application that attempts to identify and interpret what is being displayed on the screen . This interpretation is then re-presented to the user with text-to-speech, sound icons, or a Braille output device...
s, used by the
blind and partially sightedVisual impairment is vision loss to such a degree as to qualify as an additional support need through a significant limitation of visual capability resulting from either disease, trauma, or congenital or degenerative conditions that cannot be corrected by conventional means, such as refractive...
, 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 richSemantic HTML is the use of HTML markup to reinforce the semantics, or meaning, of the information in webpages rather than merely to define its presentation . Semantic HTML is processed by regular web browsers as well as by many other user agents...
as possible whether the scripts have run or not. JavaScript should not be totally reliant on
mouseIn computing, a mouse is a pointing device that functions by detecting two-dimensional motion relative to its supporting surface. Physically, a mouse consists of an object held under one of the user's hands, with one or more buttons...
-specific events so as to deny its benefits to users who either cannot use a mouse or who choose to favor the
keyboardIn computing, a keyboard is a typewriter-style keyboard, which uses an arrangement of buttons or keys, to act as mechanical levers or electronic switches...
for whatever reason. Equally, although
hyperlinkIn computing, a hyperlink is a reference to data that the reader can directly follow, or that is followed automatically. A hyperlink points to a whole document or to a specific element within a document. Hypertext is text with hyperlinks...
s and
webformsA webform on a web page allows a user to enter data that is sent to a server for processing. Webforms resemble paper or database forms because internet users fill out the forms using checkboxes, radio buttons, or text fields...
can be navigated and operated from the keyboard, accessible JavaScript should not require keyboard
eventsIn computing an event is an action that is usually initiated outside the scope of a program and that is handled by a piece of code inside the program. Typically events are handled synchronous with the program flow, that is, the program has one or more dedicated places where events are handled...
either. There are device-independent events such as
onfocus and
onchange that are preferable 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-button or the refresh event 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
nontrivialNontrivial is the opposite of trivial. In contexts where trivial has a formal meaning, nontrivial is its antonym.It is a term common among communities of engineers and mathematicians, to indicate a statement or theorem that is not obvious or easy to prove.-Examples:*In mathematics, it is often...
problem where issues become matters of debate and opinion, and where compromises are necessary in the end. However, user agents and
assistive technologiesAssistive technology or adaptive technology is an umbrella term that includes assistive, adaptive, and rehabilitative devices for people with disabilities and also includes the process used in selecting, locating, and using them...
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
sandboxIn computer security, a sandbox is a security mechanism for separating running programs. It is often used to execute untested code, or untrusted programs from unverified third-parties, suppliers, untrusted users and untrusted websites....
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 policyIn computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but...
: 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.
Cross-site vulnerabilities
A common JavaScript-related security problem is
cross-site scriptingCross-site scripting is a type of computer security vulnerability typically found in Web applications that enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same...
, or XSS, a violation of the
same-origin policyIn computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but...
. XSS vulnerabilities occur when an attacker is able to cause a target web site, such as an online banking website, to include a malicious script in the webpage presented to a victim. The script in this example can then access the banking application with the privileges of the victim, potentially disclosing secret information or transferring money without the victim's authorization. A solution to XSS vulnerabilities is to use
HTML escaping whenever displaying untrusted data.
Some browsers include partial protection against
reflected XSS attacks, in which the attacker provides a URL including malicious script. However, even users of those browsers are vulnerable to other XSS attacks, such as those where the malicious code is stored in a database. Only correct design of Web applications on the server side can fully prevent XSS.
XSS vulnerabilities can also occur because of implementation mistakes by browser authors.
Another cross-site vulnerability is
cross-site request forgeryCross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts...
or CSRF. In CSRF, code on an attacker's site tricks the victim's browser into taking actions the user didn't intend at a target site (like transferring money at a bank). It works because, if the target site relies only on cookies to authenticate requests, then requests initiated by code on the attacker's site will carry the same legitimate login credentials as requests initiated by the user. In general, the solution to CSRF is to require an authentication value in a hidden form field, and not only in the cookies, to authenticate any request that might have lasting effects. Checking the HTTP Referrer header can also help.
"JavaScript hijacking" is a type of CSRF attack in which a