JavaScript

From Bauman National Library
This page was last modified on 21 May 2016, at 22:26.
JavaScript
Paradigm

Multi-paradigm: object-oriented , generalized, functional, imperative, object-oriented, event-oriented,

Prototype п
Designed by Brendan Eich
First appeared 1995
OS Cross-platform
Filename extensions .js
Website https://www.javascript.com/
Influenced by
Self, С, Scheme, Perl, Python, Java, AWK, HyperTalk

JavaScript - prototype-based scripting programming language. It is the realization of the ECMAScript language (ECMA-262 standard). JavaScript is commonly used as an embedded language for programmatic access to application objects. The most widely used is browsers like scripting language to make interactive Web pages.The main architectural features: dynamic typing, weak typing, automatic memory management, prototype-based programming, function as a first-class objects. On JavaScript was influenced by many languages, the design goal was to make a language similar to Java, but at the same time easy to use nonprogrammer. JavaScript language does not own any company or organization that distinguishes it from a number of programming languages ​​used in web development.The name «JavaScript» is a registered trademark of Oracle Corporation.

History

Beginnings at Netscape

In December 1995, Sun and Netscape annoncent6 output JavaScript. In March 1996, Netscape implements the JavaScript engine in its Web 2.0 browser Netscape Navigator. The success of this browser contributes to the rapid adoption of JavaScript in the client oriented web development. Microsoft then responds by developing JScript, which he then included in Internet Explorer 3.0 in August 1996 for the release of its browser. Netscape then submitted JavaScript to Ecma International for standardization. Work began in November 1996 and end in June 1997 with the adoption of the new ECMAScript standard. The specifications are written in the document Standard ECMA-262. JavaScript is described as a supplement to Java in a joint statement of presse6 Netscape and Sun Microsystems, dated December 4, 1995. This initiative has helped create with the public confusion between the two languages ​​syntactically close but not in their basic concepts, and which still persists in the early 2010s.

Adoption by Microsoft

Microsoft Windows script technologies including VBScript and JScript were released in 1996. JScript, a reverse-engineered implementation of Netscape's JavaScript, was released on July 16, 1996 and was part of Internet Explorer 3, as well as being available server-side in Internet Information Server. IE3 also included Microsoft's first support for Cascading Style Sheets and various extensions to HTML, but in each case the implementation was noticeably different to that found in Netscape Navigator at the time. These differences made it difficult for designers and programmers to make a single website work well in both browsers leading to the use of 'best viewed in Netscape' and 'best viewed in Internet Explorer' logos that characterised these early years of the browser wars. JavaScript began to acquire a reputation for being one of the roadblocks to a cross-platform and standards-driven web. Some developers took on the difficult task of trying to make their sites work in both major browsers, but many could not afford the time. With the release of Internet Explorer 4, Microsoft introduced the concept of Dynamic HTML, but the differences in language implementations and the different and proprietary Document Object Models remained, and were obstacles to widespread take-up of JavaScript on the web

Standardization

In November 1996, Netscape announced that it had submitted JavaScript to Ecma International for consideration as an industry standard, and subsequent work resulted in the standardized version named ECMAScript. In June 1997, Ecma International published the first edition of the ECMA-262 specification. In June 1998, some modifications were made to adapt it to the ISO/IEC-16262 standard, and the second edition was released. The third edition of ECMA-262 was published on December 1999. Development of the fourth edition of the ECMAScript standard was never completed. The fifth edition was released in December 2009. The current edition of the ECMAScript standard is 6, released in June 2015.

What can it do?

JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages

JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

JavaScript can manipulate HTML elements - A JavaScript can read and change the content of an HTML element

JavaScript can be used to validate data - A JavaScript can be used to validate form input

JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

What can it not do?

Tasks JavaScript cannot accomplish are sampled at Dynamic Drive Forums: What you CANNOT do with JavaScript. The reasons all ultimately come down to one thing: encroachment upon someone's rights. There is some overlap, but here are the general categories:

permanent effects

It cannot write to the server because the savvy user can ultimately control its effects. It can write only cookies to the client because the programmer controls its behavior and the uninformed user cannot protect his machine in his own power. If JavaScript had permanent effects, they would invade the dominion of their subjects. (E.g., Bob's computer could become a spambot just because he visits a certain website.)

critical features

Most browsers allow the user to disable JavaScript, and some firewalls strip it from incoming pages, both for security reasons. Therefore, JavaScript is inherently unreliable. If it were reliable, remote attacks would be easier because the victims who now opt out of the risk (and who might have a higher risk of JavaScript vulnerabilities) could not do so.

secure communication

Any application which runs on a computer under the control of another party deserves a programmer's suspicion. But this is all the more true for JavaScript applications, because the code may be read and changed at will by the user (whereas most programs would require a complex and unreliable process of decompilation, source-editing, and compilation).

otherwise invasive

The browser readily AJAX|queries the page's origin client-server relationship|server on behalf of JavaScript, but no similar arrangement applies for the client machine. And JavaScript cannot change the browser's settings. Many uses exist for JavaScript (see Wikipedia:JavaScript#Uses_outside_web_pages|Uses outside web pages). This article presents the basics of every use known to the authors.

Web

Scripts may be placed in either "external" files, "internal" HTML tags, or "inline" HTML attributes. External files are widely accepted as the best among these because:

  1. They are easier to read (because the brain doesn't have to switch "modes").
  2. The browser can reuse them (because they are addressable separate from the HTML).

However, situations do exist where the others are appropriate. For example, if something needs to happen directly after a certain image loads, an external or internal script is insufficient. And external scripts are rather inconvenient on programming-oriented message boards, so the recipients of internal scripts are expected to externalize them.

External Files

Scripts may be linked from either the body or (more commonly) the head. Here is index.html:

 <html>
     <body>
         <script type="text/javascript" src="sample.js"></script>
     </body>
 </html>

And sample.js:

 document.write('Hello, world!');

Internal Tags

Tags work in much the same way as files, except the browser receives the entire page in one request (and the programmer must sift through the irrelevant language, either HTML or JavaScript, in order to do anything) if tags are used. Here is index.html:

 <html>
     <body>
         <script type="text/javascript">&amp;lt;!--
             document.write('Hello, world!');
         //--&amp;gt;</script>
     </body>
 </html>

You may have noticed that this script tag contains an HTML comment which contains the JavaScript. This is to help older browsers which were released before the tag was known and would display the JavaScript as text on the page. The two slashes are a JavaScript comment which hides the HTML comment's terminator (--&gt;) from JavaScript-capable browsers which would otherwise flag it as invalid; the initializer (&lt;!--) is not known to cause a problem.

Why the same script tag doesn't work in the head is left as an exercise for the reader.

Inline Attributes

Event-Handlers

Any HTML attribute whose name begins with on is an event-handler. Event-handlers allow JavaScript much greater flexibility than it would have without them; they notify a script that a certain thing has happened and provide some contextual information. However, note that they are also easy to use from external and internal scripts. Here is index.html:

 <html>
     <body onload="document.write('Hello, world!');">
     </body>
 </html>

javascript: URLs

Any HTML attribute which normally takes a URL can instead hold JavaScript. The most common example of this follows in a new index.html.

 <html>
     <body>
         <a href="javascript: foo();">
     </body>
 </html>

That could almost as easily be written with an onclick handler, which is more accessibility.

A language's syntax consists of its grammar and punctuation. Project: JavaScript's syntax involves values, :Category: Operators, and :Category: Words. Each value represents a datum and may be used to calculate other values via operators. Words have a few different purposes, including operations, storing values, and directly affecting a program's control flow.

Expressions

An expression is anything which may be left by itself without causing a syntax error. Each one resolves to a value (much like algebraic expressions). Any lone expression is a simple statement, and is typically terminated by either a semicolon} or a newline (or both).

Values

Values are a type of expression and include every :Category:Data types|data type. A value's data type is constantly associated with the value. Here are some useless value statements:

5;
490;

Operators

Most :Category:Operators|operators calculate values from other values; some are used to initialize values. Here are more useless statements:

5 + 4;
3 - 7;
'This is ' + 'some more text.';

Variables

Variables, commonly described as storage bins, can make the above statements useful. Variables are represented by identifiers. In JavaScript, each variable can hold exactly one item (with no practical limit on the item's size). The item is the variable's value, and it can be anything you can program. The most common operator is one which does not produce a new value; instead, it assigns a value to a variable. An assignment is a type of expression which evaluates to the assigned value.

variable = 'value';

variable will now be treated exactly as if it were 'value'. Note, however, that an exception to this applies if one variable is assigned to another:

variable1 = variable2;

Neither variable will remember the assignment when the other is changed. If you want this C-style functionality, use object#pointers|pointer objects.

A best practice exists which is to always use the var keyword before (or when) a variable is first referenced. (Note that var can be used when a variable has already been referenced; this has no effect.)

var variable = 'value';

This ensures that variable is only defined within the current scope, so a variable by the same name is not unintentionally overwritten.

Block statements

Block statements, or blocks, are used to group related statements together. A block statement begins with { and ends with }. Here is a program with a block statement:

var x = 7;
var y = 13;
{
    x = y - x;
}

At this point, block statements may seem quite useless because they do not have scope in JavaScript. However, Tutorial/Control flow statements|the next page will explain what they are good for.

A control flow statement modifies a program's control flow. A control structure additionally contains another Tutorial/Statements|statement which is executed under specified conditions, by modification and/or validation of the environment. Furthermore, loops are structures which repeat their statements while the environment is validated by a given test, or "condition." (And a loop which does not modify its environment at some point in a way which ultimately makes its condition false is an infinite loop, a common type of bug.)

Structures

if

The if statement is the most fundamental control structure. It branches according to the truth value of a Boolean Tutorial/Statements Expressions. If the condition is Truth, the supplied block will be executed. Optionally, a second statement can be provided, immediately following the if block and starting with the keyword else, which will be executed if the condition is falsy.

if (condition)
     statement
if (condition)
    statement
else
    statement

switch

The switch (or switch..case) statement tests an expression for equality with each of several values. If a matching value is found, the statements immediately after it are executed; if none of the values match and a default case exists, it is executed. If the matching case's control flow never passes over a #break|break statement and it is followed by another case, the next case is also executed.

switch(expression){
    case value1:
        ...
        break;
    case value2:
        ...
        break;
    case etc:
        ...
        break;
    default:
        ...
}

This is a good replacement for several compounded #if|if..else statements which only test the same expression for equality with several values.

Iteration_statements

Loops

while

The while is the simplest of the loops: it repeatedly checks a Boolean condition and then executes a Tutorial/Statements|statement until the condition is Truth|falsy.

while (condition)
    statement

do..while

The do..while loop is exactly the same as the while loop, with the sole exception that it checks its condition only after having already run its statement once. This is useful for situations that involve performing a calculation or getting some input, then using its result to decide whether or not to repeat the action.

do
    statement
while (condition);

for

A for loop is slightly more complex. It comprises four parts: an initialiser, a condition, a step, and a statement.

Execution of a for loop follows a set order:

  1. The initialiser is executed. This may contain a Tutorial/Statements#Variables|variable declaration.
  2. The condition is checked. If the result of this expression is falsy, the loop will exit and normal control flow will resume.
  3. The statement is executed.
  4. The step is executed. This may be any expression; the return value is ignored.
  5. Go to 2.

If you find yourself writing a #while|while loop that uses an initialiser and/or step, consider using a for instead. Any of the parts can be left blank (followed by a semicolon as appropriate), in which case they will be ignored.

for (initialiser; condition; step)
    statement

for..in

The for..in loop allows looping over all the keys of an Tutorial/Objects|object. Two caveats apply: if you are not careful to check the keys with Object.prototype.hasOwnProperty(), you may get a property on the object's prototype by accident; and for..in loops are exceedingly slow in current popular JavaScript implementations. The usual for loop should be your default choice: resort to the for..in loop only where absolutely necessary. For each element of object, the key shall be assigned to the variable key, and then the statement shall be executed.

for (var key in object)
    statement

Jumps

break

A break statement exits the specified #labels|labelled block statement or the immediately enclosing loop statement.

break;
break label;

continue

continue can only be used inside #Loops|loops. It skips the rest of the specified loop's current iteration and begins its next. If no #Labels|label is specified, the statement applies to the immediately enclosing loop

continue;
continue label;

Labels

Any block statement can be labelled by preceding it or its keyword with an identifier followed by a colon. Labels can be supplied to #Jumps|jump statements to specify a target to which to jump, but if one finds one's self using these, it's quite likely that one's code is overly complex, and the design ought to be simplified and refactored — perhaps by moving some of those inner loops into functions.

External links