Content deleted Content added
No edit summary Tag: nowiki added |
mNo edit summary |
||
Line 24:
|year=2006}}</ref>
There are two issues: five tokens can either begin a statement or be the extension of a complete statement; and five restricted productions, where line breaks are not allowed in certain positions, potentially yielding incorrect parsing.<ref name="inimino" />
The five problematic tokens are the open parenthesis "<tt>(</tt>", open bracket "<tt>[</tt>", slash "<tt>/</tt>", plus "<tt>+</tt>", and minus "<tt>-</tt>". Of these, open parenthesis is common in the [[immediately-invoked function expression]] pattern, and open bracket occurs sometimes, while others are quite rare. The example given in the spec is:<ref name="inimino" />
<syntaxhighlight lang="JavaScript">
a = b + c
(d + e).foo()
Line 37:
with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use of ''leading'' semicolons on lines starting with '<tt>(</tt>' or '<tt><nowiki>[</nowiki></tt>', so the line is not accidentally joined with the previous one. This is known as a '''defensive semicolon''', and is particularly recommended, because code may otherwise become ambiguous when it is rearranged.<ref name="inimino">"[http://inimino.org/~inimino/blog/javascript_semicolons JavaScript Semicolon Insertion: Everything you need to know]", [http://inimino.org/~inimino/blog/ ~inimino/blog/], Friday, May 28, 2010</ref><ref>"[http://mislav.uniqpath.com/2010/05/semicolons/ Semicolons in JavaScript are optional]", by Mislav Marohnić, 07 May 2010</ref> For example:
<syntaxhighlight lang="JavaScript">
a = b + c
;(d + e).foo()
Line 51:
The five restricted productions are <tt>return</tt>, <tt>throw</tt>, <tt>break</tt>, <tt>continue</tt>, and post-increment/decrement. In all cases, inserting semicolons does not fix the problem, but makes the parsed syntax clear, making the error easier to detect. <tt>return</tt> and <tt>throw</tt> take an optional value, while <tt>break</tt> and <tt>continue</tt> take an optional label. In all cases, the advice is to keep the value or label on the same line as the statement. This most often shows up in the return statement, where one might return a large object literal, which might be accidentally placed starting on a new line. For post-increment/decrement, there is potential ambiguity with pre-increment/decrement, and again it is recommended to simply keep these on the same line.
<syntaxhighlight lang="JavaScript">
return
a + b;
Line 65:
[[Comment (computer programming)|Comment]] syntax is the same as in [[C++]] and many other languages.
<syntaxhighlight lang="JavaScript">
// a short, one-line comment
Line 104:
Here is an example of variable declarations and global values:
<syntaxhighlight lang="JavaScript" enclose="div">
var x = 0; // A global variable, because it is not in any function
Line 136:
Note: undefined is considered a genuine primitive type. Unless explicitly converted, the undefined value may behave unexpectedly in comparison to other types that evaluate to false in a logical context.
<syntaxhighlight lang="JavaScript">
var test; // variable declared, but not defined, ...
// ... set to value of undefined
Line 152:
Functions like this won't work as expected:
<syntaxhighlight lang="JavaScript">
function isUndefined(x) { var u; return x === u; } // like this...
function isUndefined(x) { return x === void 0; } // ... or that second one
Line 165:
Note: Null is a true primitive-type within the JavaScript language, of which {{mono|null}} (note case) is the single value. As such, when performing checks that enforce type checking, the null value will not equal other false types. Surprisingly, {{mono|null}} is considered an object by {{mono|typeof}}.
<syntaxhighlight lang="JavaScript">
alert(null == undefined); // unenforced type during check, displays true
alert(null === undefined); // enforce type during check, displays false
Line 176:
This becomes an issue when comparing or formatting numbers. For example:
<syntaxhighlight lang="JavaScript">
alert(0.2 + 0.1 == 0.3); // displays false
alert(0.94 - 0.01); // displays 0.9299999999999999
Line 185:
Numbers may be specified in any of these notations:
<syntaxhighlight lang="JavaScript">
345; // an "integer", although there is only one numeric type in JavaScript
34.5; // a floating-point number
Line 196:
The extents [[extended real number line|'''+∞''', '''−∞''']] and '''[[NaN]]''' (Not a Number) of the number type may be obtained by two program expressions:
<syntaxhighlight lang="JavaScript">
Infinity; // positive infinity (negative obtained with -Infinity for instance)
NaN; // The Not-A-Number value, also returned as a failure in ...
Line 206:
The Number constructor, or a unary + or -, may be used to perform explicit numeric conversion:
<syntaxhighlight lang="JavaScript">
var myString = "123.456";
var myNumber1 = Number(myString);
Line 214:
When used as a constructor, a numeric ''wrapper'' object is created (though it is of little use):
<syntaxhighlight lang="JavaScript">
myNumericWrapper = new Number(123.456);
</syntaxhighlight>
Line 221:
A [[String (computer science)|string]] in JavaScript is a sequence of characters. In JavaScript, strings can be created directly (as literals) by placing the series of characters between double or single quotes. Such strings must be written on a single line, but may include escaped newline characters (such as \n). The JavaScript standard allows accent grave (back-quote, back tick) to quote multiline literal strings, but this is supported only on certain browsers as of 2016: Firefox and Chrome, but not Internet Explorer 11.{{Citation needed|date=February 2016}}
<syntaxhighlight lang="JavaScript">
var greeting = "Hello, World!";
var anotherGreeting = 'Greetings, people of Earth.';
Line 228:
You can access individual characters within a string using the {{mono|charAt}} method (provided by {{mono|String.prototype}}). This is the preferred way when accessing individual characters within a string, because it also works in non-modern browsers:
<syntaxhighlight lang="JavaScript">
var h = greeting.charAt(0);
</syntaxhighlight>
Line 234:
In modern browsers, individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays:
<syntaxhighlight lang="JavaScript">
var h = greeting[0];
</syntaxhighlight>
Line 240:
However, JavaScript strings are [[immutable object|immutable]]:
<syntaxhighlight lang="JavaScript">
greeting[0] = "H"; // Fails.
</syntaxhighlight>
Line 246:
Applying the equality operator ("==") to two strings returns true, if the strings have the same contents, which means: of the same length and containing the same sequence of characters (case is significant for alphabets). Thus:
<syntaxhighlight lang="JavaScript">
var x = "World";
var compare1 = ("Hello, " +x == "Hello, World"); // Here compare1 contains true.
Line 258:
You cannot use quotes of the same type inside quotes unless they are [[String literal#Escape character|escaped]].
<syntaxhighlight lang="JavaScript">
var x = '"Hello, World!" he said.' // Just fine.
var x = ""Hello, World!" he said." // Not good.
Line 266:
It is possible to create a string using the {{mono|String}} constructor:
<syntaxhighlight lang="JavaScript">
var greeting = new String("Hello, World!");
</syntaxhighlight>
Line 272:
These objects have a {{mono|valueOf}} method returning the primitive string wrapped within them:
<syntaxhighlight lang="JavaScript">
var s = new String("Hello !");
typeof s; // Is 'object'.
Line 280:
Equality between two {{mono|String}} objects does not behave as with string primitives:
<syntaxhighlight lang="JavaScript">
var s1 = new String("Hello !");
var s2 = new String("Hello !");
Line 299:
<div style="font-size:85%;line-height:150%;">
<syntaxhighlight lang="JavaScript">
//Automatic type coercion
alert(true == 2 ); // false... true → 1 !== 2 ← 2
Line 327:
<div style="font-size:85%;line-height:150%;">
<syntaxhighlight lang="JavaScript">
var b = new Boolean(false); // Object false {}
var t = Boolean(b); // Boolean true
Line 351:
As in the [[:Category:C programming language family|C family]], arrays use a zero-based indexing scheme: A value that is inserted into an empty array by means of the <tt>push</tt> method occupies the 0th index of the array.
<syntaxhighlight lang="JavaScript">
var myArray = []; // Point the variable myArray to a newly ...
// ... created, empty Array
Line 362:
Elements of <tt>Array</tt>s may be accessed using normal object property access notation:
<syntaxhighlight lang="JavaScript">
myArray[1]; // the 2nd item in myArray
myArray["1"];
Line 369:
The above two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:
<syntaxhighlight lang="JavaScript">
myArray.1; // syntax error
myArray["01"]; // not the same as myArray[1]
Line 376:
Declaration of an array can use either an <tt>Array</tt> literal or the <tt>Array</tt> constructor:
<syntaxhighlight lang="JavaScript">
myArray = [0, 1,, , 4, 5]; // array with length 6 and 6 elements, ...
// ... including 2 undefined elements
Line 387:
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
<syntaxhighlight lang="JavaScript">
dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
Line 395:
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both. (Technically, JavaScript does not support multidimensional arrays, but one can mimic them with arrays-of-arrays.)
<syntaxhighlight lang="JavaScript">
cats = [{color: "brown", size: "large"},
{color: "black", size: "small"}];
Line 410:
A <tt>Date</tt> object stores a signed millisecond count with zero representing 1970-01-01 00:00:00 UT and a range of ±10<sup>8</sup> days. There are several ways of providing arguments to the <tt>Date</tt> constructor. Note that months are zero-based.
<syntaxhighlight lang="JavaScript">
new Date(); // create a new Date instance representing the current time/date.
new Date(2010, 2, 1); // create a new Date instance representing 2010-Mar-01 00:00:00
Line 419:
Methods to extract fields are provided, as well as a useful <tt>toString</tt>:
<syntaxhighlight lang="JavaScript">
var d = new Date(2010, 2, 1, 14, 25, 30); // 2010-Mar-01 14:25:30;
Line 436:
Custom error messages can be created using the <tt>Error</tt> class:
<syntaxhighlight lang="JavaScript">
throw new Error("Something went wrong.");
</syntaxhighlight>
Line 442:
Nested within conditional statements, such instantiations can substitute for try/catch blocks:
<syntaxhighlight lang="JavaScript">
var emailAddress = prompt("Please enter your e-mail address:", "");
if (!emailAddress || emailAddress.length == 0) {
Line 518:
===Regular expression===
{{main|Regular expression}}
<syntaxhighlight lang="JavaScript">
/expression/.test(string); // returns Boolean
"string".search(/expression/); // returns position Number
Line 530:
====Character classes====
<syntaxhighlight lang="JavaScript">
// \d - digit
// \D - non digit
Line 550:
====Character matching====
<syntaxhighlight lang="JavaScript">
// A...Z a...z 0...9 - alphanumeric
// \u0000...\uFFFF - Unicode hexadecimal
Line 565:
====Repeaters====
<syntaxhighlight lang="JavaScript">
// ? - 0 or 1 match
// * - 0 or more
Line 583:
====Anchors====
<syntaxhighlight lang="JavaScript">
// ^ - string starts with
// $ - string ends with
Line 592:
====Subexpression====
<syntaxhighlight lang="JavaScript">
// ( ) - groups characters
Line 600:
====Flags====
<syntaxhighlight lang="JavaScript">
// /g - global
// /i - ignore upper/lower case
Line 611:
====Advanced methods====
<syntaxhighlight lang="JavaScript">
my_array = my_string.split(my_delimiter);
// example
Line 622:
====Capturing groups====
<syntaxhighlight lang="JavaScript">
var myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;
var results = myRe.exec("The date and time are 2009-09-08 09:37:08.");
Line 636:
Every function in JavaScript is an instance of the <tt>Function</tt> constructor:
<syntaxhighlight lang="JavaScript">
//x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
var add = new Function('x', 'y', 'return x + y');
Line 645:
The add function above may also be defined using a function expression:
<syntaxhighlight lang="JavaScript">
var add = function(x, y) {
return x + y;
Line 655:
There exists a shorthand for assigning a function expression to a variable, and is as follows:
<syntaxhighlight lang="JavaScript">
function add(x, y) {
return x + y;
Line 665:
A function instance has properties and methods.
<syntaxhighlight lang="JavaScript">
function subtract(x, y) {
return x - y;
Line 683:
The '+' operator is [[Operator overloading|overloaded]]: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number.
<syntaxhighlight lang="JavaScript">
// Concatenate 2 strings
alert('He' + 'llo'); // displays Hello
Line 729:
|}
<syntaxhighlight lang="JavaScript">
var x = 1;
alert(++x); // displays: 2
Line 757:
[[Assignment (computer science)|Assignment]] of [[primitive type]]s
<syntaxhighlight lang="JavaScript">
var x = 9;
x += 1;
Line 773:
Assignment of object types
<syntaxhighlight lang="JavaScript">
/**
* To learn JavaScript objects…
Line 802:
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leaves that are to receive the substructures of the assigned value.
<syntaxhighlight lang="JavaScript">
var a, b, c, d, e;
[a, b] = [3, 4];
Line 836:
When comparing variables that are objects they are considered to be different, if their objects are not the same. This is the case, even if the values of them are the same. So:
<syntaxhighlight lang="JavaScript">
var obj1 = {a: 1};
var obj2 = {a: 1};
Line 860:
The Boolean function can be used to explicitly convert to a primitive of type <tt>Boolean</tt>:
<syntaxhighlight lang="JavaScript">
// Only empty strings return false
alert(Boolean("") === false);
Line 884:
The NOT operator evaluates its operand as a Boolean and returns the negation. Using the operator twice in a row, as a [[double negative]], explicitly converts an expression to a primitive of type Boolean:
<syntaxhighlight lang="JavaScript">
alert( !0 === Boolean(!0)); alert(Boolean(!0) === !!1); alert(!!1 === Boolean(1));
alert(!!0 === Boolean(0)); alert(Boolean(0) === !1); alert(!1 === Boolean(!1));
Line 893:
The ternary operator can also be used for explicit conversion:
<syntaxhighlight lang="JavaScript">
alert([] == false); alert([] ? true : false); // “truthy”, but the comparison uses [].toString()
alert([0] == false); alert([0]? true : false); // [0].toString() == "0"
Line 905:
Expressions that use features such as post–incrementation, (<tt>i++</tt>), have an anticipated [[Side effect (computer science)|side effect]]. JavaScript provides [[short-circuit evaluation]] of expressions; the right operand is only executed, if the left operand does not suffice to determine the value of the expression.
<syntaxhighlight lang="JavaScript">
alert(a || b); // When a is true, there is no reason to evaluate b.
alert(a && b); // When a is false, there is no reason to evaluate b.
Line 913:
In early versions of JavaScript and [[JScript]], the binary logical operators returned a Boolean value (like most C–derived programming languages). However, all contemporary implementations return one of their operands instead:
<syntaxhighlight lang="JavaScript">
alert(a || b); // if a is true, return a, otherwise return b
alert(a && b); // if a is false, return a, otherwise return b
Line 920:
Programmers who are more familiar with the behavior in C might find this feature surprising, but it allows for a more concise expression of patterns like [[null coalescing operator|null coalescing]]:
<syntaxhighlight lang="JavaScript">
var s = t || "(default)"; // assigns t, or the default value, if t is null, empty, etc.
</syntaxhighlight>
Line 963:
Examples:
<syntaxhighlight lang="JavaScript">
str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
Line 977:
===If … else===
<syntaxhighlight lang="JavaScript">
if (expr) {
//statements;
Line 991:
The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the ''if'' statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what ''if'' is to statements.
<syntaxhighlight lang="JavaScript">
result = condition ? expression : alternative;
</syntaxhighlight>
Line 997:
is the same as:
<syntaxhighlight lang="JavaScript">
if (condition) {
result = expression;
Line 1,010:
The syntax of the JavaScript [[Control flow#Choice|switch statement]] is as follows:
<syntaxhighlight lang="JavaScript">
switch (expr) {
case SOMEVALUE:
Line 1,034:
The syntax of the JavaScript [[for loop]] is as follows:
<syntaxhighlight lang="JavaScript">
for (initial; condition; loop statement) {
/*
Line 1,046:
or
<syntaxhighlight lang="JavaScript">
for (initial; condition; loop statement(iteration)) // one statement
</syntaxhighlight>
Line 1,053:
The syntax of the JavaScript <code>[[Foreach|for … in loop]]</code> is as follows:
<syntaxhighlight lang="JavaScript">
for (var property_name in some_object) {
//statements using some_object[property_name];
Line 1,066:
The syntax of the JavaScript [[while loop]] is as follows:
<syntaxhighlight lang="JavaScript">
while (condition) {
statement1;
Line 1,078:
The syntax of the JavaScript <code>[[do while loop|do … while loop]]</code> is as follows:
<syntaxhighlight lang="JavaScript">
do {
statement1;
Line 1,090:
The with statement adds all of the given object's properties and methods into the following block's scope, letting them be referenced as if they were local variables.
<syntaxhighlight lang="JavaScript">
with (document) {
var a = getElementById('a');
Line 1,106:
JavaScript supports nested labels in most implementations. Loops or blocks can be labelled for the break statement, and loops for <tt>continue</tt>. Although [[goto]] is a reserved word,<ref>ECMA-262, Edition 3, 7.5.3 Future Reserved Words</ref> goto is not implemented in JavaScript.
<syntaxhighlight lang="JavaScript">
loop1: for (var a = 0; a < 10; a++) {
if (a == 4) {
Line 1,135:
A [[function (programming)|function]] is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If you exit the function without a return statement, the value {{mono|undefined}} is returned.
<syntaxhighlight lang="JavaScript">
function gcd(segmentA, segmentB) {
var diff = segmentA - segmentB;
Line 1,152:
The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value {{mono|undefined}} (that can be implicitly cast to false). Within the function, the arguments may also be accessed through the {{mono|arguments}} object; this provides access to all arguments using indices (e.g. {{code|lang=javascript|code=arguments[0], arguments[1], ... arguments[n]}}), including those beyond the number of named arguments. (While the arguments list has a <tt>.length</tt> property, it is ''not'' an instance of {{mono|Array}}; it does not have methods such as {{mono|.slice()}}, {{mono|.sort()}}, etc.)
<syntaxhighlight lang="JavaScript">
function add7(x, y) {
if (!y) {
Line 1,165:
Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed.
<syntaxhighlight lang="JavaScript">
var obj1 = {a : 1};
var obj2 = {b : 2};
Line 1,178:
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore, they implement full [[closure (computer science)|closure]]s by remembering the outer function's local variables even after the outer function has exited.
<syntaxhighlight lang="JavaScript">
var v = "Top";
var bar, baz;
Line 1,200:
Objects can be created using a constructor or an object literal. The constructor can use either a built-in Object function or a custom function. It is a convention that constructor functions are given a name that starts with a capital letter:
<syntaxhighlight lang="JavaScript">
// Constructor
var anObject = new Object();
Line 1,214:
Object literals and array literals allow one to easily create flexible data structures:
<syntaxhighlight lang="JavaScript">
var myStructure = {
name: {
Line 1,236:
Note that in the example below, Foo is simply assigning values to slots, some of which are functions. Thus it can assign different functions to different instances. There is no prototyping in this example.
<syntaxhighlight lang="JavaScript">
function px() { return this.prefix + "X"; }
Line 1,272:
Example: Manipulating an object:
<syntaxhighlight lang="JavaScript">
function MyObject(attributeA, attributeB) {
this.attributeA = attributeA;
Line 1,298:
The constructor itself is referenced in the object's prototype's ''constructor'' slot. So,
<syntaxhighlight lang="JavaScript">
function Foo() {}
// Use of 'new' sets prototype slots (for example,
Line 1,334:
Some implementations allow the prototype to be accessed or set explicitly using the {{mono|__proto__}} slot as shown below.
<syntaxhighlight lang="JavaScript">
function Base() {
this.anOverride = function() { alert("Base::anOverride()"); };
Line 1,364:
The following shows clearly how references to prototypes are ''copied'' on instance creation, but that changes to a prototype can affect all instances that refer to it.
<syntaxhighlight lang="JavaScript">
function m1() { return "One"; }
function m2() { return "Two"; }
Line 1,397:
The <code>try … catch … finally</code> statement catches [[exception handling|exceptions]] resulting from an error or a throw statement. Its syntax is as follows:
<syntaxhighlight lang="JavaScript">
try {
// Statements in which exceptions might be thrown
Line 1,415:
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in [[Java (programming language)|Java]]:
<syntaxhighlight lang="JavaScript">
try { statement; }
catch (e if e == "InvalidNameException") { statement; }
Line 1,426:
<!-- This needs verification -->
<syntaxhighlight lang="JavaScript">
onerror = function (errorValue, url, lineNr) {...; return true;};
</syntaxhighlight>
Line 1,436:
Evaluates expression string parameter, which can include assignment statements. Variables local to functions can be referenced by the expression.
<syntaxhighlight lang="JavaScript">
(function foo() {
var x = 7;
Line 1,449:
==References==
<references />
==Further reading==
|