Javascript

AjustarCompartirImprimirCitar

JavaScript (commonly abbreviated JS) is an interpreted programming language, a dialect of the ECMAScript standard. It is defined as object-oriented, prototype-based, imperative, weakly-typed, and dynamic.

It is mainly used on the client side, implemented as part of a web browser allowing user interface enhancements and dynamic web pages and JavaScript on the server side (Server-side JavaScript or SSJS). Its use in applications external to the web, for example in PDF documents, desktop applications (mostly widgets) is also significant.

Since 2012, all modern browsers fully support ECMAScript 5.1, a version of JavaScript. Older browsers support at least ECMAScript 3. The sixth edition was released in July 2015.

JavaScript was designed with a syntax similar to C++ and Java, though it adopts names and conventions from the Java programming language. However, Java and JavaScript have different semantics and purposes. Their relationship is purely commercial, after the purchase of the creator of Java (Sun Microsystems) from Netscape Navigator (creator of LiveScript) and the name change of the programming language.

All modern browsers interpret the JavaScript code embedded in web pages. To interact with a web page, the JavaScript language is provided with an implementation of the Document Object Model (DOM). Javascript is the only programming language that is natively understood by browsers.

Traditionally it had been used in HTML web pages to perform operations and only within the framework of the client application, without access to server functions. Currently it is widely used to send and receive information from the server along with the help of other technologies such as AJAX. JavaScript is interpreted in the user agent at the same time that the statements are downloaded along with the HTML code.

Since the release in June 1997 of the ECMAScript 1 standard, there have been versions 2, 3 and 5, which is the most widely used today (4 was abandoned). In June 2015, ECMAScript 6 was closed and released.

History

Birth of JavaScript

JavaScript was originally developed by Brendan Eich of Netscape under the name Mocha, which was later renamed to LiveScript, eventually becoming JavaScript. The name change roughly coincided with the time Netscape added support for Java technology to its Netscape Navigator web browser in version 2002 in December 1995. The naming caused confusion, giving the impression that the language is an extension of Java., and was considered by many as a marketing strategy for Netscape to gain prestige and innovate in the field of new web programming languages.

"JAVASCRIPT" is a registered trademark of Oracle Corporation. It is used under license for products created by Netscape Communications and existing entities such as the Mozilla Foundation.

Microsoft named its JavaScript dialect "JScript" to avoid branding issues. JScript was adopted in version 3.0 of Internet Explorer, released in August 1996, and included support for Y2K date functions, a difference from those that were based at the time. The dialects may seem so similar that the terms "JavaScript" and "JScript" are often used interchangeably, but the JScript specification is incompatible with the ECMA specification in many respects.

To avoid these incompatibilities, the World Wide Web Consortium designed the Document Object Model (DOM) standard, which incorporates Konqueror, Internet Explorer versions 6 and Netscape Navigator, Opera version 7, Mozilla Application Suite and Mozilla Firefox since its first version.[citation required]

In 1997 the authors proposed JavaScript to be adopted as a standard by the European Computer Manufacturers' Association ECMA, which despite its name is not European but international, based in Geneva. In June 1997 it was adopted as an ECMA standard, under the name of ECMAScript. Soon after also as an ISO standard.

JavaScript on the server side

Netscape introduced a server-side script implementation with Netscape Enterprise Server, released in December 1994 (shortly after the release of JavaScript for web browsers). Starting in the mid-2000s, there has been a proliferation of server-side JavaScript implementations. Node.js is one of the notable examples of server-side JavaScript being used in major projects.

Later developments

JavaScript has become one of the most popular and widely used programming languages on the internet. Initially, however, many developers balked at the language because its intended audience included article publishers and other hobbyists, among other reasons. The advent of Ajax brought JavaScript back to prominence and attracted the attention of many other programmers. As a result of this, there has been a proliferation of a set of general purpose libraries and frameworks, improved JavaScript programming practices, and increased use of JavaScript outside of web browsers, as seen with the proliferation of side-by-side JavaScript environments. from the server. In January 2009, the CommonJS project was launched with the goal of specifying a library for use by CommonJS primarily for development outside of the web browser.

In June 2015, the ECMAScript 6 standard was closed and published with irregular support between browsers and that provides JavaScript with advanced features that were missing and are commonly used in other languages, for example, modules for code organization, true classes for object-oriented programming, arrow expressions, iterators, generators, or promises for asynchronous programming.

ECMAScript version 7 is known as ECMAScript 2016, and is the latest version available, released in June 2016. This is the first version using a new annual release procedure and development process open.

Features

The following features are common to all implementations that conform to the ECMAScript standard, unless you explicitly specify otherwise.

Imperative and structured

JavaScript supports much of the C programming structure (for example, if statements, for loops, switch statements, etc.). With one caveat, in part: in C, the scope of variables extends to the block in which they are defined; however JavaScript does not support this, since the scope of variables is that of the function in which they were declared. This changes with ECMAScript 2015 as it adds support for block scoping via the let keyword. Like C, JavaScript makes a distinction between expressions and statements. A syntactical difference from C is the automatic insertion of semicolons, that is, in JavaScript the semicolons that end a statement can be omitted.

Dynamics

Dynamic dye
As in most scripting languages, the type is associated with value, not variable. For example, a variable x at a given time may be tied to a number and later, redirected to a chain. JavaScript is compatible with several ways to check the type of an object, including duck typing. One way of knowing it is through the keyword typeof.
Objective
JavaScript is formed almost entirely by objects. JavaScript objects are associative arrays, improved with the inclusion of prototypes (see below). The names of the properties of objects are chain-type keys: obj.x = 10 and obj['x'] = 10 are equivalent, being syntactic sugar notation with point. Property and its values can be created, changed or eliminated in execution time. Most properties of an object (and those that are included by the prototypic inheritance chain) can be listed by means of loop instruction for... in. JavaScript has a small number of predefined objects as they are Function and Date.
Performance time assessment
JavaScript includes the function eval which allows to evaluate expressions expressed as chains in execution time. It is therefore recommended that eval is used with caution and that you choose to use the function JSON.parse() to the extent possible, it can be much safer.

Functional

First class functions
Functions are usually called first class citizens; they are objects in themselves. As such, they possess properties and methods, as .call() and .bind(). An anature function is a defined function within another. This is created every time the external function is invoked. In addition, each function created forms a closing; it is the result of evaluating an area containing one or more variables dependent on another external sphere, including constants, local variables and arguments of the external function callte. The outcome of the evaluation of the closure is part of the internal status of each function object, even after the external function concludes its evaluation.

Prototypical

Prototypes
JavaScript uses prototypes instead of classes for inheritance use. It is possible to emulate many of the features that the classes provide in languages oriented to traditional objects through prototypes in JavaScript.
Functions as object builders
The functions also behave as builders. Prefix a call to function with the keyword new create a new instance of a prototype, which inherit the properties and methods of the builder (including the properties of the prototype Object). ECMAScript 5 offers the method Object.createallowing the explicit creation of an instance without having to automatically inherit from the Object prototype (in ancient environments the prototype of the created object may appear as null). The property prototype the builder determines the object used for the internal prototype of the new objects created. New methods can be added by modifying the prototype of the object used as a builder. Predefined builders in JavaScript, such as Array u ObjectThey also have prototypes that can be modified. Although this is possible it is considered a bad practice to modify the prototype Object since most of the objects in Javascript inherit the methods and properties of the object prototype, objects which can expect these have not been modified.

Other features

Performance environment
JavaScript usually depends on the environment in which it is executed (e.g. in a web browser) to offer objects and methods by which scripts can interact with the "outside world". In fact, it depends on the environment to be able to provide the ability to include or import scripts (e.g., in HTML through the tag ). (This is not a language feature, but it is common in most JavaScript implementations.)
Variadic functions
An indefinite number of parameters can be passed to the function. The function can access them through the parameters or also through the local object arguments. Variadic functions can also be created using the method .apply().
Functions as methods
Unlike many object-oriented languages, there is no distinction between definition of function and definition of method. Rather, the distinction occurs during the call to the function; a function can be called as a method. When a function is called as a method of an object, the keyword thiswhich is a local variable to the function, represents the object that invoked that function.
Arrays and the literal definition of objects
Like many script languages, arrays and objects (associative spells in other languages) can be created with an abbreviated syntax. In fact, these verbatims form the basis of JSON data format.
Regular expressions
JavaScript is also compatible with regular expressions in a similar way to Perl, which provide a concise and powerful syntax for text manipulation that is more sophisticated than the functions incorporated into string-type objects.

Vendor-specific extensions

JavaScript is officially under the organization of the Mozilla Foundation, and new language features are added periodically. However, only some JavaScript engines support these features:

  • Property get and set (also compatible with WebKit, Opera, ActionScript and Rhino).
  • Clauses catch conditional.
  • Python's adopted iterative protocol.
  • Corrutinas also adopted from Python.
  • Generation of lists and expressions by understanding also adopted by Python.
  • Set the area to block through the keyword let.
  • Disstructuring of arrays and objects (limited pattern pairing form).
  • Specific expressions in functions (function(args) expr).
  • ECMAScript for XML (E4X), an extension that adds native XML compatibility to ECMAScript.

Syntax and semantics

The latest version of the language is ECMAScript 2016 released at the end of June 17, 2016.

Simple examples

Variables in JavaScript are defined using the var keyword:

var x; // defines variable x, although it has no value assigned by defaultvar and = 2; // defines the variable and assigns the value 2 to it

Consider the comments in the example above, which are preceded with 2 forward slashes.

There is no functionality for I/O included in the language; the runtime environment already provides it. The ECMAScript specification in its 5.1 edition mentions:

... in fact, there are no provisions in this specification for external data entry or output for computed results.

However, most runtimes have an object called console that can be used to print by the debug console output stream. Here's a simple program that prints "Hello world!":

console.log("Hello world!");

A recursive function:

function factorial(n) { if (n  0) { return 1; ! return n  factorial(n - 1);!

Examples of an anonymous function (or lambda function) and a closure:

var displayClosure = function() { var count = 0; return function () { return +count; };!var inc = displayClosure();inc(); // returns 1inc(); // returns 2inc(); // returns 3

Self-invoking expressions allow functions to pass variables to it by parameter within their own closures.

var v;v = 1;var getValue = (function(v) { return function() {return v;.v));v = 2;getValue(); // 1

More advanced examples

The following code demonstrates various features of JavaScript.

/* Find the minimum common multiple (MCM) of two numbers */function LCMCalculator(x, and) { //builder function var CheckInt = function (x) { // interior function if (x % 1 = 0) { throw new TypeError(x + "is not an integer."); // launches an exception ! return x; }; this.a = CheckInt(x) // points and comma are optional this.b = CheckInt(and);!// The prototype of the object instances created by the builder is that of the “prototype” property of the builder.LCMCalculator.prototype = { // object defined as literal builder: LCMCalculator, // when we reassign a prototype, we correctly establish your building property gcd: function () { // method that calculates the maximum common divider // Euclides Algorithm: var a = Math..abs(this.a), b = Math..abs(this.b), t; if (a . b) { // we exchange variables t = b; b = a; a = t; ! while (b = 0) { t = b; b = a % b; a = t; ! // We only need to calculate the MCD once, therefore 'redefine' this method. // (It is not really a redefinition—it is defined in one's own instance, therefore // this.gcd refers to this 'redefinition' instead of LCMCalculator.prototype.gcd). // In addition, 'gcd' == "gcd", this['gcd'] === this.gcd this[chuckles]'gcd'] = function () { return a; }; return a; } // The names of the properties of the object can be specified with strings delimited with simple (') or double quotes (“). "lcm" : function () { // The names of the variables do not collision with the properties of the object. For example: Δlcmint is not 日本語this.lcm. // Do not use 日本語this.a * this.b78 to avoid problems with floating comma calculations. var lcm = this.a / this.gcd()  this.b; // We only need to calculate MCM once, therefore "redefining" this method. this.lcm = function () { return lcm; }; return lcm; } toString: function () { return "LCMCalculator: a = + this.a + ", b = + this.b; !};// We define a generic function to print a result; this implementation only works on web browsersfunction output(x) { document.body.appendChild(document.createTextNode(x)); document.body.appendChild(document.createElement('br'));!// Note: The methods.map() and.forEach() of the Array prototype are defined in JavaScript 1.6.// These methods are used here to demonstrate the inherent functional nature of language.[25, 55], [chuckles]21, 56], [chuckles]22, 58], [chuckles]28, 56]].map(function (pair) { // Verbatim construction of an Array + mapping function. return new LCMCalculator(pair[chuckles]0], pair[chuckles]1]);}).draw(function (a, b) { // order the collection through this function return a.lcm() - b.lcm();}).forEach(function (obj) { output(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());});

The following example shows the output that should be displayed in a 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 write functions that are embedded or included in HTML pages and that interact with the Document Object Model (DOM) of the page. Some simple examples of this use are:

  • Upload new content for the page or send data to the server via AJAX without reloading the page (e.g., a social network can allow the user to send status updates without leaving the page).
  • Animation of the page elements, make them disappear, change their size, move them, etc.
  • Interactive content, for example, games and audio and video playback.
  • Validation of the input values of a web form to make sure they are acceptable before being sent to the server.
  • Transmission of information about user reading habits and browsing activities to various websites. Web pages often do so for web analysis, ad tracking, customization or other purposes.

Because the JavaScript code can be executed locally in the 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 that HTML alone cannot, such as keystrokes. Applications like Gmail take advantage of this: most of the user interface logic is written in JavaScript, sending requests to the server (for example, the content of an email message). The growing trend for the use of Ajax programming similarly exploits this technique.

A JavaScript engine (also known as a 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, called SpiderMonkey, is implemented in C. It has since been updated (in JavaScript 1.5) to comply with ECMA-262 edition 3. The Rhino engine, primarily created by Norris Boyd (formerly of Netscape, now at Google) is an implementation of JavaScript in Java. Rhino, like SpiderMonkey, is ECMA-262 Edition 3 compliant.

A web browser is by far the most common hosting environment for JavaScript. Web browsers often create non-native, runtime-dependent objects to represent the Document Object Model (DOM) in JavaScript. The web server is another common service environment. A JavaScript web server typically exposes its own objects to represent 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 most popular browsers share support for, it has become a language that many frameworks in other languages compile to, even though JavaScript was not designed for such purposes. Despite the performance limitations inherent in its dynamic nature, the increased speed of JavaScript engines has made JavaScript a surprisingly feasible environment for compilation.

Script Example

The following is a brief example of a web page (conforming to the standards of the HTML5 standard) that uses JavaScript for DOM handling:

html.html.head .goal charset="utf-8" .titleSimple exampletitlehead.body .h1 id="header"This is JavaScripth1 .script document.body.appendChild(document.createTextNode('Hello World!')); var h1 = document.getElementById('header'); // contains the reference to the tag ≤1 h1 = document.getElementsByTagName('h1')[0]; // acceding to the same element ≤2 script .noscriptYour browser does not support JavaScript, or JavaScript is disabled.noscriptbodyhtml

Compatibility Considerations

Because JavaScript runs in many different environments, an important part of testing and debugging is testing and verifying that the JavaScript code works correctly in multiple browsers. The DOM interface for accessing and manipulating web pages is not part of the ECMAScript standard, or of JavaScript itself. The DOM is defined by the standardization efforts of the W3C, an independent organization. In practice, the implementations that different browsers make of JavaScript differ both from each other and from the standards of the standard.

To address these differences, JavaScript authors may have been able to write standards-compliant code that would also be able to run correctly in most browsers, or failing that, could at least be coded. capable of verifying the presence of certain browser functionalities and that it behaves differently if said functionality were not available. There are cases in which two browsers can implement the same feature, but with different behavior, a fact that Developers may find it helpful to detect which browser is currently running and thus change the behavior of their writing to match. Developers also often use libraries or tools that take into account differences between browsers.

Also, the scripts may not work for some users. For example, a user can:

  • Use an old browser without full compatibility with the DOM API,
  • Use a PDA browser or mobile phone that cannot run JavaScript
  • Have the execution of disabled JavaScript, as safety precaution,
  • Using a voice browser due to, for example, a visual disability.

To support these users, web developers often create pages that are fault tolerant based on the user agent (browser type) that does not support JavaScript. In particular, the page should still be useful even without the extra features that JavaScript would have added. An alternative approach that many find preferable is to first create content using technologies that work in all browsers, and enhance content for users who have enabled JavaScript.

Accessibility

Assuming that the user has not disabled JavaScript code execution, client-side JavaScript should be written both for the purpose of improving the experiences of visually or physically impaired visitors, and to avoid hiding information from them visitors.

Screen readers, used by the blind and partially sighted, can be taken into account by JavaScript to access and read the DOM elements of the page. The HTML code written should be as concise, navigable, and semantically rich as possible, whether JavaScript is executed or not.

JavaScript should not be totally dependent on browser mouse events and should be accessible to users who do not want to use the (computer) mouse to navigate or who choose to use the keyboard only. There are device-independent events, such as onfocus and onchange that are preferable in most cases.

JavaScript must not be used to create confusion or disorientation to the web user. For example, modifying or disabling normal browser functionality, such as changing the way the navigate back button or the refresh event behaves, are practices that are generally best avoided. Similarly, triggering events that the user may not be aware of reduces the user's sense of control and causes unexpected changes to the page content.

Often, the process of providing a complex web page with the highest degree of accessibility possible becomes a non-trivial problem where many issues end up being debated and opinionated, requiring everyone's commitment to the end. However, user agents and technologies to support people with disabilities are constantly evolving and new guidelines and information continue to be published on the web.

Security

JavaScript and the DOM allow programmers to misuse it to introduce scripts that execute code with malicious content without the user's consent, thereby compromising user security.

Browser developers account for this risk by using two constraints. First, the scripts run in a sandbox where only web-related actions can be performed, not general-purpose programming tasks like file creation. Second, it is limited by the same origin policy: scripts from one website do not have access to information sent to another website (from another domain) such as usernames, passwords or cookies. Most JavaScript security flaws are related to violations of either of these two restrictions.

There are projects like AdSafe or Secure ECMA script (SES) that provide higher levels of security, especially in code created by third parties (such as ads).

The Content Secure Policy (CSP) is the primary method intended to ensure that only trusted code can be executed on a web page.

Cross-site vulnerabilities

A common security issue in JavaScript is cross-site scripting, or XSS, a violation of the same-origin policy. XSS vulnerabilities allow an attacker to inject JavaScript code into web pages visited by the user. One of these websites could be that of a bank, the attacker being able to access the banking application with the victim's privileges, which could reveal secret information or transfer money without the victim's authorization. One workaround for XSS vulnerabilities is to use HTML escaping when displaying information from untrusted sources.

Some browsers include partial protection against reflected XSS attacks (the attacker is in the web request itself). The attacker provides a URL including malicious code. However, even browser users are vulnerable to other XSS attacks, such as those in which malicious code is stored in a database. Only the correct design of web applications on the server side can totally prevent XSS. XSS vulnerabilities can also occur due to execution errors by browser developers.

Another vulnerability is Cross Site Request Forgery, or CSRF. In CSRF, the attacking website's code tricks the victim's browser, allowing the attacker to make requests on the victim's behalf, making it impossible for the target application (for example, a bank doing a money transfer) to know. if the request has been made voluntarily by the user or by a CSRF attack.

The attack works because if the target site uses only cookies to authenticate the victim's requests, requests initiated by the attacker's code will have the same legitimate access credentials as user-initiated requests..

In general, the solution to CSRF is to introduce a hidden form field whose value is used to perform authentication, and not just via cookies, on requests that may have lasting effects. Checking the HTTP referer header can also help.

"JavaScript Hijacking" is a type of CSRF attack in which a <script> on the attacker's website exploits a vulnerability in the victim's site page that causes it to return private information, in the form of JSON or JavaScript code. Possible solutions are:

  • that a authentication token is required in the parameters of the POST and GET requests for those requests that require returning private information from the user.
  • use POST and never GET for applications that return private information

Development tools

In JavaScript, having a debugger becomes necessary when developing large, non-trivial applications. Since there can be implementation differences between different browsers (especially regarding the DOM), it is useful to have access to a debugger for each of the browsers that our web application will target.

Web debuggers are available for Internet Explorer, Firefox, Safari, Google Chrome, and Opera.

There are three debuggers available for Internet Explorer: Microsoft Visual Studio is the most advanced of the three, followed closely by Microsoft Script Editor (a component of Microsoft Office) and finally Microsoft Script Debugger, which is much more basic. than the other two, although it is free. The free Microsoft Visual Web Developer Express IDE offers a limited version of JavaScript debugging functionality in Microsoft Visual Studio. Internet Explorer has included developer tools since version 8 (shown by pressing the F12 key). Web applications within Firefox can be debugged using the Firebug add-on or the old Venkman debugger. Firefox also has a basic error console built in, which logs and evaluates JavaScript. It also logs CSS errors and warnings. Opera includes a suite of tools called Dragonfly. WebKit's Web Inspector includes a JavaScript debugger used in Safari, along with a modified version of Google Chrome.

There are some debugging aids, also written in JavaScript and built to run on the Web. An example is the JSLint program, developed by Douglas Crockford, who has written extensively on the language. JSLint analyzes the JavaScript code so that it conforms to a set of standards and guidelines and that ensure its proper functioning and maintainability.

Contenido relacionado

Datagram

A datagram is a packet of data that constitutes the smallest block of information in a datagram-switched network, which is one of two types of packet-switched...

Help:Using LaTeX

Visually, MathJax provides better results. The quality of the typography is much higher and certain problems are eliminated, such as the different size of the...

File (computing)

A file or file computer is a sequence of bytes stored on a device. A file is identified by a name and the description of the folder or directory that contains...
Más resultados...
Tamaño del texto: