The examples below make use of the log function of the console object present in most browsers for [[Standard streams#Standard output .28stdout.29|standard text output]].
The JavaScript [[standard library]] lacks an official standard text output function (with the exception of <code>document.write</code>). Given that JavaScript is mainly used for [[client-side scripting]] within modern [[web browser]]s, and that almost all Web browsers provide the alert function, <ttcode>alert</ttcode> can also be used, but is not commonly used.
==Origins==
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 "<ttcode>(</ttcode>", open bracket "<ttcode>[</ttcode>", slash "<ttcode>/</ttcode>", plus "<ttcode>+</ttcode>", and minus "<ttcode>-</ttcode>". Of these, the 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<!-- The blog is not a spec[ification] --> is:<ref name="inimino" />
<syntaxhighlight lang="javascript">
with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use of ''leading'' semicolons on lines starting with '<ttcode>(</ttcode>' or '<ttcode><nowiki>[</nowiki></ttcode>', 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, 28 May 2010</ref><ref>"[http://mislav.uniqpath.com/2010/05/semicolons/ Semicolons in JavaScript are optional]", by Mislav Marohnić, 7 May 2010</ref> For example:
<syntaxhighlight lang="javascript">
Initial semicolons are also sometimes used at the start of JavaScript libraries, in case they are appended to another library that omits a trailing semicolon, as this can result in ambiguity of the initial statement.
The five restricted productions are <ttcode>return</ttcode>, <ttcode>throw</ttcode>, <ttcode>break</ttcode>, <ttcode>continue</ttcode>, 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. <ttcode>return</ttcode> and <ttcode>throw</ttcode> take an optional value, while <ttcode>break</ttcode> and <ttcode>continue</ttcode> 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">
==Variables==
[[Variable (programming)|Variable]]s in standard JavaScript have no [[Type system|type]] attached, so any value (each ''value'' has a type) can be stored in any variable. Starting with [[ECMAScript#6th Edition – ECMAScript 2015|ES6]], the 6th version of the language, variables could be declared with <code>var</code> for function scoped variables, and <code>let</code> or <code>const</code> which are for [[block scope|block level]] variables. Before ES6, variables could only be declared with a <code>var</code> statement. Values assigned to variables declared with <code>const</code> cannot be changed, but its properties can. A variable's [[Identifier (computer languages)|identifier]] must start with a letter, underscore (<ttcode>_</ttcode>), or dollar sign (<ttcode>$</ttcode>), while subsequent characters can also be digits (<ttcode>0-9</ttcode>). JavaScript is case sensitive, so the uppercase characters "A" through "Z" are different from the lowercase characters "a" through "z".
Starting with JavaScript 1.5, [[ISO 8859-1]] or [[Unicode]] letters (or <ttcode>\uXXXX</ttcode> Unicode escape sequences) can be used in identifiers.<ref>{{cite web | url=https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals&revision=22#Variables | title=Values, Variables, and Literals - MDC | date=16 September 2010 | publisher=Mozilla Developer Network | access-date=1 February 2020 | archive-url=https://web.archive.org/web/20110629131728/https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals%26revision%3D22#Variables | archive-date=29 June 2011 | url-status=dead }}</ref> In certain JavaScript implementations, the at sign (@) can be used in an identifier, but this is contrary to the specifications and not supported in newer implementations. {{Citation needed|date=January 2021}}
===Scoping and hoisting===
===Array===
An [[Array data type|Array]] is a JavaScript object prototyped from the <ttcode>Array</ttcode> constructor specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (for example, <ttcode>join</ttcode>, <ttcode>slice</ttcode>, and <ttcode>push</ttcode>).
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 <ttcode>push</ttcode> method occupies the 0th index of the array.
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Arrays have a <ttcode>length</ttcode> property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated, if one creates a property with an even larger index. Writing a smaller number to the <ttcode>length</ttcode> property will remove larger indices.
Elements of <ttcode>Array</ttcode>s may be accessed using normal object property access notation:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Declaration of an array can use either an <ttcode>Array</ttcode> literal or the <ttcode>Array</ttcode> constructor:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
[[Array data structure|Arrays]] are implemented so that only the defined elements use memory; they are "[[sparse array]]s". Setting {{code|lang=javascript|code=myArray[10] = 'someThing'}} and {{code|lang=javascript|code=myArray[57] = 'somethingOther'}} only uses space for these two elements, just like any other object. The <ttcode>length</ttcode> of the array will still be reported as 58. The maximum length of an array is 4,294,967,295 which corresponds to 32-bit binary number (11111111111111111111111111111111)<sub>2</sub>.
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
===Date===
A <ttcode>Date</ttcode> 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 <ttcode>Date</ttcode> constructor. Note that months are zero-based.
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Methods to extract fields are provided, as well as a useful <ttcode>toString</ttcode>:
<syntaxhighlight lang="javascript">
===Error===
Custom error messages can be created using the <ttcode>Error</ttcode> class:
<syntaxhighlight lang="javascript">
===Function===
Every function in JavaScript is an instance of the <ttcode>Function</ttcode> constructor<!-- There's also constructor for async / generator functions: (async()=>{}).constructor gets AsyncFunction, (async function*(){}).constructor gets AsyncGeneratorFunction, (function*(){}).constructor gets GeneratorFunction -->:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain the <ttcode>this</ttcode> of the global object instead of inheriting it from where it was called / what it was called on, unlike the <ttcode>function() {}</ttcode> expression.
<syntaxhighlight lang="javascript">
{| class="wikitable"
|-
| align="center" | <ttcode>+</ttcode> || addition
|-
| align="center" | <ttcode>-</ttcode> || subtraction
|-
| align="center" | <ttcode>*</ttcode> || multiplication
|-
| align="center" | <ttcode>/</ttcode> || division (returns a floating-point value)
|-
| align="center" | <ttcode>%</ttcode> || modulo (returns the remainder)
|-
| align="center" | <ttcode>**</ttcode> || exponentiation
|}
{| class="wikitable"
|-
| align="center" | <ttcode>+</ttcode> || unary conversion of string to number
|-
| align="center" | <ttcode>-</ttcode> || unary negation (reverses the sign)
|-
| align="center" | <ttcode>++</ttcode> || increment (can be prefix or postfix)
|-
| align="center" | <ttcode>--</ttcode> || decrement (can be prefix or postfix)
|}
{| class="wikitable"
|-
| align="center" | <ttcode>=</ttcode> || assign
|-
| align="center" | <ttcode>+=</ttcode> || add and assign
|-
| align="center" | <ttcode>-=</ttcode> || subtract and assign
|-
| align="center" | <ttcode>*=</ttcode> || multiply and assign
|-
| align="center" | <ttcode>/=</ttcode> || divide and assign
|-
| align="center" | <ttcode>%=</ttcode> || modulo and assign
|-
| align="center" | <ttcode>**=</ttcode> || exponentiation and assign
|}
==== Spread/rest operator ====
The ECMAScript 2015 standard introduces the "<ttcode>...</ttcode>" operator, for the related concepts of "spread syntax"<ref>{{cite web|url=https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator|title=Spread syntax}}</ref> and "rest parameters"<ref>{{cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters| title = rest parameters}}</ref>
'''Spread syntax''' provides another way to destructure arrays. It indicates that the elements in a specified array should be used as the parameters in a function call or the items in an array literal.
In other words, "<ttcode>...</ttcode>" transforms "<ttcode>[...foo]</ttcode>" into "<ttcode>[foo[0], foo[1], foo[2]]</ttcode>", and "<ttcode>this.bar(...foo);</ttcode>" into "<ttcode>this.bar(foo[0], foo[1], foo[2]);</ttcode>".
<syntaxhighlight lang="javascript" line="1">
</syntaxhighlight>
When <ttcode>...</ttcode> is used in a function ''declaration'', it indicates a '''rest parameter'''. The rest parameter must be the final named parameter in the function's parameter list. It will be assigned an <ttcode>Array</ttcode> containing any arguments passed to the function in excess of the other named parameters. In other words, it gets "the rest" of the arguments passed to the function (hence the name).
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Rest parameters are similar to Javascript's <ttcode>arguments</ttcode> object, which is an array-like object that contains all of the parameters (named and unnamed) in the current function call. Unlike <ttcode>arguments</ttcode>, however, rest parameters are true <ttcode>Array</ttcode> objects, so methods such as <ttcode>.slice()</ttcode> and <ttcode>.sort()</ttcode> can be used on them directly.
The <ttcode>...</ttcode> operator can only be used with <ttcode>Array</ttcode> objects. (However, there is a proposal to extend it to <ttcode>Object</ttcode>s in a future ECMAScript standard.<ref>{{cite web|url=https://sebmarkbage.github.io/ecmascript-rest-spread/ |archive-url=https://web.archive.org/web/20160809104217/https://sebmarkbage.github.io/ecmascript-rest-spread/ |url-status=dead |archive-date=2016-08-09 | title=Ecmascript}}</ref>)
===Comparison===
{| class=wikitable
|-
| align="center" | <ttcode>==</ttcode> || equal
|-
| align="center" | <ttcode>!=</ttcode> || not equal
|-
| align="center" | <ttcode>></ttcode> || greater than
|-
| align="center" | <ttcode>>=</ttcode> || greater than or equal to
|-
| align="center" | <ttcode><</ttcode> || less than
|-
| align="center" | <ttcode><=</ttcode> || less than or equal to
|-
| align="center" | <ttcode>===</ttcode> || identical (equal and of same type)
|-
| align="center" | <ttcode>!==</ttcode> || not identical
|}
===Logical===
JavaScript provides four logical operators:
* unary [[negation]] (<ttcode>NOT = !a</ttcode>)
* binary [[logical disjunction|disjunction]] (<ttcode>OR = a || b</ttcode>) and [[logical conjunction|conjunction]] (<ttcode>AND = a && b</ttcode>)
* ternary [[Conditional (programming)|conditional]] (<ttcode>c ? t : f</ttcode>)
In the context of a logical operation, any expression evaluates to true except the following''':'''
* Strings: <ttcode>""</ttcode>, <ttcode><nowiki>''</nowiki></ttcode>,
* Numbers: <ttcode>0</ttcode>, <ttcode>-0</ttcode>, <ttcode>NaN</ttcode>,
* Special: <ttcode>null</ttcode>, <ttcode>undefined</ttcode>,
* Boolean: <ttcode>false</ttcode>.
The Boolean function can be used to explicitly convert to a primitive of type <ttcode>Boolean</ttcode>:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Expressions that use features such as post–incrementation (<ttcode>i++</ttcode>) 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">
{| class="wikitable"
|-
| align="center" | <ttcode>??=</ttcode>
| Nullish assignment
|-
| align="center" | <ttcode><nowiki>||=</nowiki></ttcode>
| Logical Or assignment
|-
| align="center" | <ttcode>&&=</ttcode>
| Logical And assignment
|}
{| class="wikitable"
|-
| align="center" | <ttcode>&</ttcode> || AND
|-
| align="center" | <ttcode>|</ttcode> || OR
|-
| align="center" | <ttcode>^</ttcode> || XOR
|-
|!
|NOT
|-
| align="center" | <ttcode><<</ttcode> || shift left (zero fill at right)
|-
| align="center" | <ttcode>>></ttcode> || shift right (sign-propagating); copies of the<br />leftmost bit (sign bit) are shifted in from the left
|-
| align="center" | <ttcode>>>></ttcode> || shift right (zero fill at left). For positive numbers,<br /><ttcode>>></ttcode> and <ttcode>>>></ttcode> yield the same result.
|}
{| class="wikitable"
|-
| align="center" | <ttcode>~</ttcode> || NOT (inverts the bits)
|}
{| class="wikitable"
|-
| align="center" | <ttcode>&=</ttcode> || and
|-
| align="center" | <ttcode>|=</ttcode> || or
|-
| align="center" | <ttcode>^=</ttcode> || xor
|-
| align="center" | <ttcode><<=</ttcode> || shift left (zero fill at right)
|-
| align="center" | <ttcode>>>=</ttcode> || shift right (sign-propagating); copies of the<br />leftmost bit (sign bit) are shifted in from the left
|-
| align="center" | <ttcode>>>>=</ttcode> || shift right (zero fill at left). For positive numbers,<br /><ttcode>>>=</ttcode> and <ttcode>>>>=</ttcode> yield the same result.
|}
{| class="wikitable"
|-
| align="center" | <ttcode>=</ttcode> || assignment
|-
| align="center" | <ttcode>+</ttcode> || concatenation
|-
| align="center" | <ttcode>+=</ttcode> || concatenate and assign
|}
===Compound statements===
A pair of curly brackets <ttcode>{ }</ttcode> and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
===If ... else===
</syntaxhighlight>
* <ttcode>break;</ttcode> is optional; however, it is usually needed, since otherwise code execution will continue to the body of the next case block.
* Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
* String literal values can also be used for the case values.
===Labels===
JavaScript supports nested labels in most implementations. Loops or blocks can be labelled for the break statement, and loops for <ttcode>continue</ttcode>. Although <ttcode>[[goto]]</ttcode> is a reserved word,<ref>ECMA-262, Edition 3, 7.5.3 Future Reserved Words</ref> <ttcode>goto</ttcode> is not implemented in JavaScript.
<syntaxhighlight lang="javascript">
Functions are [[first class object]]s and may be assigned to other variables.
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 <ttcode>.length</ttcode> property, it is ''not'' an instance of {{mono|Array}}; it does not have methods such as {{mono|.slice()}}, {{mono|.sort()}}, etc.)
<syntaxhighlight lang="javascript">
For convenience, types are normally subdivided into ''primitives'' and ''objects''. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values ("slots" in [[prototype-based programming]] terminology). Objects may be thought of as [[associative arrays]] or hashes, and are often implemented using these data structures. However, objects have additional features, such as a prototype chain{{clarify|date=January 2012}}, which ordinary associative arrays do not have.
JavaScript has several kinds of built-in objects, namely <ttcode>Array</ttcode>, <ttcode>Boolean</ttcode>, <ttcode>Date</ttcode>, <ttcode>Function</ttcode>, <ttcode>Math</ttcode>, <ttcode>Number</ttcode>, <ttcode>Object</ttcode>, <ttcode>RegExp</ttcode> and <ttcode>String</ttcode>. Other objects are "host objects", defined not by the language, but by the runtime environment. For example, in a browser, typical host objects belong to the DOM (window, form, links, etc.).
===Creating objects===
</syntaxhighlight>
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a special <ttcode>prototype</ttcode> property, as discussed in the "Inheritance" section below.)
Object deletion is rarely used as the scripting engine will [[Garbage collection (computer science)|garbage collect]] objects that are no longer being referenced.
|