JavaScript syntax: Difference between revisions

Content deleted Content added
Tag: Reverted
Stormgaze (talk | contribs)
m added code tags to improve consistency across article
 
(53 intermediate revisions by 28 users not shown)
Line 1:
{{Short description|Set of rules defining correctly structured programs}}
{{Update|date=November 2020|reason=New features/versions now in JavaScript}}2
{{Multiple issues|
{{Very long|rps=79|date=May 2019}}
{{Update|date=November 2020|reason=New features/versions now in JavaScript}}2
}}
[[File:Source code in Javascript.png|thumb|300px|A snippet of [[Javascript]] code with keywords highlighted in different colors]]
{{Use dmy dates|date=April 2022}}
{{Use American English|date=April 2025}}
 
[[File:Source code in Javascript.png|thumb|300px|A snippet of [[JavascriptJavaScript]] code with keywords [[Syntax highlighting|highlighted]] in different colors]]
 
The '''[[Syntax (programming languages)|syntax]] of [[JavaScript]]''' is the set of rules that define a correctly structured JavaScript program.
 
The examples below make use of the <code>console.log()</code> 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, <code>alert</code> can also be used, but is not commonly used.
 
==Origins==
[[Brendan Eich]] summarized the ancestry of the [https://jsonlinecompiler.com/javascript/javascript-syntax/ syntax] in the first paragraph of the [https://jsonlinecompiler.com/javascript/javascript-introduction/ JavaScript 1.1] specification<ref>[{{Cite web |url=http://hepunx.rl.ac.uk/~adye/jsspec11/intro.htm#1006028 |title=JavaScript 1.1 specification] |access-date=19 April 2006 |archive-date=26 February 2017 |archive-url=https://web.archive.org/web/20170226200426/http://hepunx.rl.ac.uk/~adye/jsspec11/intro.htm#1006028 |url-status=live }}</ref><ref>{{cite web|title=Chapter 1. Basic JavaScript|url=http://speakingjs.com/es5/ch01.html|access-date=2020-09-22 September 2020|website=speakingjs.com|archive-date=10 February 2022|archive-url=https://web.archive.org/web/20220210041253/http://speakingjs.com/es5/ch01.html|url-status=dead}}</ref> as follows:
{{Quote|[https://jsonlinecompiler.com/javascript/javascript-introduction/ JavaScript] borrows most of its syntax from [[Java (programming language)|Java]], but also inherits from [[Awk]] and [[Perl]], with some indirect influence from [[Self (programming language)|Self]] in its object prototype system.}}
 
==Basics==
 
===Case sensitivity===
JavaScript is [[Case sensitivity|case sensitive]]. It is common to start the name of a [[#Constructors|constructor]] with a [[CamelCase|capitalisedcapitalized]] letter, and the name of a function or variable with a lower-case letter.
 
Example:
Line 28:
console.log(A); // throws a ReferenceError: A is not defined
</syntaxhighlight>
 
Try this example code on [[https://jsonlinecompiler.com/javascript-online-editor/ JavaScript online compiler & Editor]].
 
===Whitespace and semicolons===
Unlike in [[C (programming language)|C]], whitespace in JavaScript source can directly impact [[Semantics (computer science)|semantics]]. [[Semicolon]]s end statements in JavaScript. Because of [[Lexical analysis#Semicolon insertion|automatic semicolon insertion]] (ASI), some statements that are well formed when a newline is [[Parsing|parsed]] will be considered complete, as if a semicolon were inserted just prior to the newline. Some authorities advise supplying statement-terminating semicolons explicitly, because it may lessen unintended effects of the automatic semicolon insertion.<ref>{{cite book
|title=JavaScript: The definitive Guide
|url=https://archive.org/details/javascript00libg_297
Line 41 ⟶ 39:
|quote=Omitting semicolons is not a good programming practice; you should get into the habit of inserting them.
|isbn=978-0-596-10199-2
|year=2006}}</ref>|publisher="O'Reilly Media, Inc."
}}</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.
Line 54 ⟶ 53:
// a = b + c(d + e).foo();
</syntaxhighlight>
Try this example code on [[https://jsonlinecompiler.com/javascript-online-editor/ JavaScript online compiler & Editor]].
 
with the suggestion that the preceding statement be terminated with a semicolon.
 
Line 68 ⟶ 65:
// (d + e).foo();
</syntaxhighlight>
Try this example code on [[https://jsonlinecompiler.com/javascript-online-editor/ JavaScript online compiler & Editor]].
 
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.
 
Line 84 ⟶ 79:
// return a + b;
</syntaxhighlight>
Try this example code on [[https://jsonlinecompiler.com/javascript-online-editor/ JavaScript online compiler & Editor]].
 
===Comments===
[[Comment (computer programming)|Comment]] syntax is the same as in [[C++]], [[Swift (programming language)|Swift]] and many other programming languages.
{{Main|Comment (computer programming)}}
 
[[Comment (computer programming)|Comment]] syntax is the same as in [[C++]], [[Swift (programming language)|Swift]] and many other languages.
Single-line comments begin with <code>//</code> and continue until the end of the line. A second type of comments can also be made; these start with <code>/*</code> and end with <code>*/</code> and can be used for multi-line comments.
 
A third type of comment, the hashbang comment, starts with <code>#!</code> and continues until the end of the line. They are only valid at the start of files and are intended for use in [[command-line interface|CLI]] environments.<ref>{{cite web |last1=Farias |first1=Bradley |title=Hashbang Grammar |url=https://github.com/tc39/proposal-hashbang |website=GitHub |access-date=13 July 2025}}</ref>
 
<syntaxhighlight lang="javascript">
//#! a short, one-lineHashbang comment
 
/*/ this is a long, multiOne-line comment
about my script. May it one day
be great. */
 
/* Multi-line
/* Comments /* may not be nested */ Syntax error */
comment */
</syntaxhighlight>
 
Line 103 ⟶ 99:
{{Main|Variable (programming)}}
 
[[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 itstheir properties can. <code>var</code> should no longer be used since <code>let</code> and <code>const</code> are supported by modern browsers.<ref>{{Cite web |date=9 May 2023-05-09 |title=Storing the information you need — Variables - Learn web development {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables |access-date=2023-06-23 June 2023 |website=developer.mozilla.org |language=en-US}}</ref> A variable's [[Identifier (computer languages)|identifier]] must start with a letter, underscore (<code>_</code>), or dollar sign (<code>$</code>), while subsequent characters can also be digits (<code>0-9</code>). 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 <code>\uXXXX</code> 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}}
Line 109 ⟶ 105:
===Scoping and hoisting===
 
Variables declared with <code>var</code> are [[lexical scoping|lexically scoped]] at a [[function scope|function level]], while ones with <code>let</code> or <code>const</code> have a [[block scope|block level]] scope. Since declarations are processed before any code is executed, a variable can be assigned to and used prior to being declared in the code.<ref>{{cite web |title=JavaScript Hoisting |publisher=[[W3Schools]] |url=https://www.w3schools.com/js/js_hoisting.asp |quote=In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared. |access-date=17 December 2021 |archive-date=31 March 2022 |archive-url=https://web.archive.org/web/20220331225545/https://www.w3schools.com/js/js_hoisting.asp |url-status=live }}</ref> This is referred to as ''{{visible anchor|hoisting}}'', and it is equivalent to variables being [[Forward declaration|forward declared]] at the top of the function or block.<ref>"[http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html JavaScript Scoping and Hoisting] {{Webarchive|url=https://web.archive.org/web/20210508121632/http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html |date=8 May 2021 }}", [http://www.adequatelygood.com/about.html Ben Cherry] {{Webarchive|url=https://web.archive.org/web/20210228091155/http://www.adequatelygood.com/about.html |date=28 February 2021 }}, ''[http://www.adequatelygood.com/ Adequately Good] {{Webarchive|url=https://web.archive.org/web/20220308081510/http://www.adequatelygood.com/ |date=8 March 2022 }},'' 8 February 2010-02-08</ref><!-- Might not explain scoping very well -->
 
With <code>var</code>, <code>let</code>, and <code>const</code> statements, only the declaration is hoisted; assignments are not hoisted. Thus a {{code|lang=javascript|code=var x = 1}} statement in the middle of the function is equivalent to a {{code|lang=javascript|code=var x}} declaration statement at the top of the function, and an {{code|lang=javascript|code=x = 1}} assignment statement at that point in the middle of the function. This means that values cannot be accessed before they are declared; [[forward reference]] is not possible. With <code>var</code> a variable's value is <code>undefined</code> until it is initialized. Variables declared with <code>let</code> or <code>const</code> cannot be accessed until they have been initialized, so referencing such variables before will cause an error.<!-- Some sources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting. Referencing a let or const will not throw if there's a type of. An exception to the typeof exception is "const x = x;", which you can try in the console. -->
Line 143 ⟶ 139:
function f() {
var z = 'foxes', r = 'birds'; // 2 local variables
m = 'fish'; // global, because it wasn'twas not declared anywhere before
 
function child() {
Line 209 ⟶ 205:
Note: There is no built-in language literal for undefined. Thus {{code|lang=javascript|code=(x === undefined)}} is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it is legal for someone to write {{code|lang=javascript|code=var undefined = "I'm defined now";}}. A more robust approach is to compare using {{code|lang=javascript|code=(typeof x === 'undefined')}}.
 
Functions like this won'twill not work as expected:
 
<syntaxhighlight lang="javascript">
Line 217 ⟶ 213:
</syntaxhighlight>
 
Here, calling <code>isUndefined(my_var)</code> raises a {{mono|ReferenceError}} if {{mono|my_var}} is an unknown identifier, whereas {{code|lang=javascript|code=typeof my_var === 'undefined'}} doesn'tdoes not.
 
===Number===
Line 243 ⟶ 239:
</syntaxhighlight>
 
There's is also a numeric separator, {{mono|_}} (the underscore), introduced in ES2021:
 
<syntaxhighlight lang="javascript">
// Note: Wikipedia syntax doesn'tdoes not support numeric separators yet
1_000_000_000; // Used with big numbers
1_000_000.5; // Support with decimals
Line 256 ⟶ 252:
0xFFFF_FFFF_FFFF_FFFE;
 
// But youusers can'tcannot use them next to a non-digit number part, or at the start or end
_12; // Variable is not defined (the underscore makes it a variable identifier)
12_; // Syntax error (cannot be at the end of numbers)
12_.0; // Syntax error (doesn'tdoes not make sense to put a separator next to the decimal point)
12._0; // Syntax error
12e_6; // Syntax error (next to "e", a non-digit. Doesn'tDoes not make sense to put a separator at the start)
1000____0000; // Syntax error (next to "_", a non-digit. Only 1 separator at a time is allowed
</syntaxhighlight>
Line 305 ⟶ 301:
console.log(nan !== nan); // true
 
// YouUsers can use the isNaN methods to check for NaN
console.log(isNaN("converted to NaN")); // true
console.log(isNaN(NaN)); // true
Line 313 ⟶ 309:
 
===BigInt===
In JavaScript, regular numbers are represented with the IEEE 754 floating point type, meaning integers can only safely be stored if the value falls between <code>Number.MIN_SAFE_INTEGER</code> and <code>Number.MAX_SAFE_INTEGER</code>. <ref>{{cite web |title=Number - JavaScript | url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number |website=MDN Web Docs |access-date=13 July 2025}}</ref> BigInts instead represent [[integers]] of any size, allowing programmers to store integers too high or low to be represented with the IEEE 754 format.<ref name="bigint-mdn">{{cite web |title=BigInt - Javascript |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt |website=MDN Web Docs |access-date=13 July 2025}}</ref>
BigInts can be used for arbitrarily large [[integer]]s. Especially whole numbers larger than 2<sup>53</sup> - 1, which is the largest number JavaScript can reliably represent with the Number primitive and represented by the Number.MAX_SAFE_INTEGER constant.
 
There are two ways to declare a BigInt value. An <code>n</code> can be appended to an integer, or the <code>BigInt</code> function can be used:<ref name="bigint-mdn" />
When dividing BigInts, the results are [[Truncation|truncated]].
 
<syntaxhighlight lang="javascript">
const a = 12345n; // Creates a variable and stores a BigInt value of 12345
const b = BigInt(12345);
</syntaxhighlight>
 
=== String ===
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 (<code>"</code>) or single (<code>'</code>) quotes. Such strings must be written on a single line, but may include escaped newline characters (such as <code>\n</code>). The JavaScript standard allows the [[Grave accent#Use in programming|backquote]] character (<code>`</code>, a.k.a. grave accent or backtick) to quote multiline literal strings, but this is supported only on certainas browserswell as ofembedded 2016:expressions Firefoxusing andthe Chrome,syntax but not Internet Explorer 11<code>${''expression''}</code>.<ref>{{cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals|title=Template literals|website=MDN Web Docs|language=en-US|access-date=20184 November 2023|archive-05date=31 March 2022|archive-02url=https://web.archive.org/web/20220331204510/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals|url-status=live}}</ref>
 
<syntaxhighlight lang="javascript">
const greeting = "Hello, World!";
const anotherGreeting = 'Greetings, people of Earth.';
const aMultilineGreeting = `Warm regards,
John Doe.`
 
// Template literals type-coerce evaluated expressions and interpolate them into the string.
const templateLiteral = `This is what is stored in anotherGreeting: ${anotherGreeting}.`;
console.log(templateLiteral); // 'This is what is stored in anotherGreeting: 'Greetings, people of Earth.''
console.log(`You are ${Math.floor(age)=>18 ? "allowed" : "not allowed"} to view this web page`);
</syntaxhighlight>
 
Line 393 ⟶ 401:
Automatic type coercion by the equality comparison operators (<code>==</code> and <code>!=</code>) can be avoided by using the type checked comparison operators (<code>===</code> and <code>!==</code>).
 
When type conversion is required, JavaScript converts {{mono|Boolean}}, {{mono|Number}}, {{mono|String}}, or {{mono|Object}} operands as follows:<ref>{{cite web | url=https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators | title=Comparison Operators - MDC Doc Center | publisher=Mozilla | date=5 August 2010 | access-date=5 March 2011 | archive-date=4 May 2012 | archive-url=https://web.archive.org/web/20120504005400/https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators | url-status=live }}</ref>
;{{small|Number and String}}: The string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
;{{small|Boolean}}: If one of the operands is a Boolean, the Boolean operand is converted to 1 if it is {{mono|true}}, or to 0 if it is {{mono|false}}.
;{{small|Object}}: If an object is compared with a number or string, JavaScript attempts to return the default value for the object. An object is converted to a primitive String or Number value, using the {{mono|.valueOf()}} or {{mono|.toString()}} methods of the object. If this fails, a runtime error is generated.
 
==== Boolean type conversion ====
{{anchor|truthy and falsy}}
{{further|Truthy (computing)}}
[[Douglas Crockford]] advocates the terms "'''truthy'''" and "'''falsy'''" to describe how values of various types behave when evaluated in a logical context, especially in regard to edge cases.<ref>{{cite web | url=http://javascript.crockford.com/style2.html | title=The Elements of JavaScript Style | publisher=Douglas Crockford | access-date=5 March 2011 | archive-date=17 March 2011 | archive-url=https://web.archive.org/web/20110317074944/http://javascript.crockford.com/style2.html | url-status=live }}</ref>
The binary logical operators returned a Boolean value in early versions of JavaScript, but now they return one of the operands instead. The left–operand is returned, if it can be evaluated as : {{mono|false}}, in the case of [[logical conjunction|conjunction]]: (<code>a && b</code>), or {{mono|true}}, in the case of [[logical disjunction|disjunction]]: (<code>a || b</code>); otherwise the right–operand is returned. Automatic type coercion by the comparison operators may differ for cases of mixed Boolean and number-compatible operands (including strings that can be evaluated as a number, or objects that can be evaluated as such a string), because the Boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a Boolean primitive by doubling the logical [[negation|negation operator]]: ({{mono|!!}}), using the {{mono|Boolean()}} function, or using the [[Conditional (programming)|conditional operator]]: (<code>c ? t : f</code>).
 
Line 444 ⟶ 455:
 
===Symbol===
Symbols are a feature introduced in [[ES6]]. Each symbol is guaranteed to be a unique value, and they can be used for [[Encapsulation (computer programming)|encapsulation]].<ref>{{cite web |last1=Orendorff |first1=Jason |title=ES6 In Depth: Symbols |url=https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/ |website=Mozilla Hacks |access-date=13 July 2025}}</ref>
New in ECMAScript6. A ''Symbol'' is a unique and immutable identifier.
 
Example:
Line 481 ⟶ 492:
There are also ''well known symbols''. <!-- TODO: Add table or something -->
 
One of which is <code>Symbol.iterator</code>; if something implements <code>Symbol.iterator</code>, it's is iterable:
 
<syntaxhighlight lang="javascript">
Line 534 ⟶ 545:
</syntaxhighlight>
 
The above two are equivalent. It's is not possible to use the "dot"-notation or strings with alternative representations of the number:
 
<syntaxhighlight lang="javascript">
Line 548 ⟶ 559:
// Array literals
myArray = [1, 2]; // length of 2
myArray = [1, 2,]; // same array - YouUsers can also have an extra comma at the end
 
// It's is also possible to not fill in parts of the array
myArray = [0, 1, /* hole */, /* hole */, 4, 5]; // length of 6
myArray = [0, 1, /* hole */, /* hole */, 4, 5,]; // same array
Line 589 ⟶ 600:
<syntaxhighlight lang="javascript">
new Date(); // create a new Date instance representing the current time/date.
new Date(2010, 32, 1); // create a new Date instance representing 2010-Mar-01 00:00:00
new Date(2010, 32, 1, 14, 25, 30); // create a new Date instance representing 2010-Mar-01 14:25:30
new Date("2010-3-1 14:25:30"); // create a new Date instance from a String.
</syntaxhighlight>
Line 603 ⟶ 614:
+ d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds());
 
// Built-in toString returns something like 'Mon Mar1 01March, 2010 14:25:30 GMT-0500 (EST)':
console.log(d);
</syntaxhighlight>
Line 661 ⟶ 672:
| {{mono|Math.cos(Math.PI/4)}} || 0.70711 || [[Trigonometric functions|Cosine]]
|-
| {{mono|Math.exp}}(1) }}|| 2.7183 || [[Exponential function]]: {{mvar|e}} raised to this power
|-
| {{mono|Math.floor(1.9)}} || 1 || Floor: round down to largest integer ≤ argument
Line 839 ⟶ 850:
</syntaxhighlight>
 
Hoisting allows youusers to use the function before it is "declared":
 
<syntaxhighlight lang="javascript">
Line 947 ⟶ 958:
</syntaxhighlight>
 
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again:
 
<syntaxhighlight lang="javascript">
Line 953 ⟶ 964:
console.log((-x%5+5)%5); // displays 3
</syntaxhighlight>
YouUsers could also do:
<syntaxhighlight lang="javascript">
const x = 17;
Line 1,013 ⟶ 1,024:
message(); // displays 7 7 2
 
object_3.a = 5; // object_3 doesn'tdoes not change object_2
message(); // displays 7 7 5
 
Line 1,037 ⟶ 1,048:
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
const arr = [];
({baz: [arr[0], arr[3]], foo: a, bar: b}) = e);
console.log(`${a},${b},${arr}`); // displays: 5,6,Baz,,,Content
[a, b] = [b, a]; // swap contents of a and b
Line 1,049 ⟶ 1,060:
==== Spread/rest operator ====
 
The ECMAScript 2015 standard introducesintroduced the "<code>...</code>" array operator, for the related concepts of "spread syntax"<ref>{{citeCite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operatorSpread_syntax|title=Spread syntax (...) - JavaScript &#124; MDN|date=25 September 2023|website=developer.mozilla.org}}</ref> and "rest parameters".<ref>{{cite web| url = https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters| title = rest parameters| date = 9 September 2024| access-date = 29 September 2016| archive-date = 30 May 2018| archive-url = https://web.archive.org/web/20180530204951/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters| url-status = live}}</ref> Object spreading was added in ECMAScript 2018.
 
'''Spread syntax''' provides another way to destructure arrays and objects. ItFor 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. For objects, it can be used for merging objects together or overriding properties.
 
In other words, "<code>...</code>" transforms "<code>[...foo]</code>" into "<code>[foo[0], foo[1], foo[2]]</code>", and "<code>this.bar(...foo);</code>" into "<code>this.bar(foo[0], foo[1], foo[2]);</code>", and "<code>{ ...bar }</code>" into <code>{ prop: bar.prop, prop2: bar.prop2 }</code>.
 
<syntaxhighlight lang="javascript" line="1">
Line 1,073 ⟶ 1,084:
}
 
// YouUsers can use it even if it passes more parameters than the function will use
foo(...a); // "1:2:3" → foo(a[0], a[1], a[2], a[3]);
 
// YouUsers can mix it with non-spread parameters
foo(5, ...a, 6); // "5:1:2" → foo(5, a[0], a[1], a[2], a[3], 6);
 
Line 1,082 ⟶ 1,093:
// assigns the array to arg1, and nothing to the other parameters.
foo(a); // "1,2,3,4:undefined:undefined"
 
const bar = { a: 1, b: 2, c: 3 };
 
// This would copy the object
const copy = { ...bar }; // copy = { a: 1, b: 2, c: 3 };
 
// "b" would be overridden here
const override = { ...bar, b: 4 }; // override = { a: 1, c: 3, b: 4 }
</syntaxhighlight>
 
Line 1,096 ⟶ 1,115:
 
Rest parameters are similar to Javascript's <code>arguments</code> object, which is an array-like object that contains all of the parameters (named and unnamed) in the current function call. Unlike <code>arguments</code>, however, rest parameters are true <code>Array</code> objects, so methods such as <code>.slice()</code> and <code>.sort()</code> can be used on them directly.
 
The <code>...</code> operator can only be used with <code>Array</code> objects. (However, there is a proposal to extend it to <code>Object</code>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===
Line 1,232 ⟶ 1,249:
 
=== Bitwise ===
{{Expand section|date=April 2011}}
JavaScript supports the following '''binary [[Bitwise operation|bitwise operators]]''':
 
Line 1,243 ⟶ 1,259:
| align="center" | <code>^</code> || XOR
|-
| align="center" | <code>!</code> || NOT
|!
|NOT
|-
| align="center" | <code>&lt;&lt;</code> || shift left (zero fill at right)
Line 1,356 ⟶ 1,371:
 
===Switch statement===
{{Main|Switch statement}}
The syntax of the JavaScript [[Control flow#Choice|switch statement]] is as follows:
 
Line 1,416 ⟶ 1,430:
* Iterates through all enumerable properties of an object.
* Iterates through all used indices of array including all user-defined properties of array object, if any. Thus it may be better to use a traditional for loop with a numeric index when iterating over arrays.
* There are differences between the various Web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice, each browser returns a slightly different set of properties during introspection. It is useful to test for a given property using {{nowrap|{{code|lang=javascript|code=if (some_object.hasOwnProperty(property_name)) { ... } }}}}. Thus, adding a method to the array prototype with {{nowrap|{{code|lang=javascript|code=Array.prototype.newMethod = function() {...} }}}} may cause <code>for ... in</code> loops to loop over the method's name.
 
===While loop===
Line 1,459 ⟶ 1,473:
 
===Labels===
JavaScript supports nested labels in most implementations. Loops or blocks can be labelledlabeled for the break statement, and loops for <code>continue</code>. Although <code>[[goto]]</code> is a reserved word,<ref>ECMA-262, Edition 3, 7.5.3 Future Reserved Words</ref> <code>goto</code> is not implemented in JavaScript.
 
<syntaxhighlight lang="javascript">
Line 1,483 ⟶ 1,497:
{{Main|Function (computer programming)}}
 
A [[Function (computer programming)|function]] is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If youa exituser exits the function without a return statement, the value {{mono|undefined}} is returned.
 
<syntaxhighlight lang="javascript+genshitext">
function gcd(number1, number2) {
if (isNaN(number1*number2)) throw TypeError("Non-Numeric arguments not allowed.");
number1 = Math.round(number1);
number2 = Math.round(number2);
Line 1,545 ⟶ 1,559:
console.log(t); // Top
</syntaxhighlight>
 
An ''anonymous function'' is simply a function without a name and can be written either using function or arrow notation. In these equivalent examples an anonymous function is passed to the '''map''' function and is applied to each of the elements of the array.<ref>{{cite web |last=Yadav |first=Amitya |date=4 October 2024 |title=Named function vs Anonymous Function Impacts |url=https://aditya003-ay.medium.com/named-function-vs-anonymous-function-impacts-94e2472ed7bb |website=medium.com |access-date=19 February 2025}}</ref>
 
<syntaxhighlight lang="javascript">
[1,2,3].map(function(x) { return x*2;); //returns [2,4,6]
[1,2,3].map((x) => { return x*2;}); //same result
</syntaxhighlight>
 
A ''generator function'' is signified placing an * after the keyword ''function'' and contains one or more ''yield'' statements. The effect is to return a value and pause execution at the current state. Declaring an generator function returns an iterator. Subsequent calls to ''iterator.next()'' resumes execution until the next ''yield''. When the iterator returns without using a yield statement there are no more values and the '''done''' property of the iterator is set to '''true'''.<ref> {{cite web |author=<!-- not stated --> |title=function* |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*|website=mdm web docs |access-date=23 February 2025}}</ref>
 
With the exception of [[iOS]] devices from Apple, generators are not implemented for browsers on mobile devices. <ref> {{cite web |author=<!-- not stated --> |title=ES6 Generators |url=https://caniuse.com/?search=generator|website=medium.com |access-date=23 February 2025}}</ref>
 
<syntaxhighlight lang="javascript">
function* generator() {
yield "red";
yield "green";
yield "blue";
}
 
let iterator=generator();
let current;
 
while(current=iterator.next().value)
console.log(current); //displays red, green then blue
console.log(iterator.next().done) //displays true
</syntaxhighlight>
 
 
===Async/await===
Line 1,550 ⟶ 1,591:
 
==Objects==
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[[Prototype-based chain{{clarifyprogramming|date=Januaryprototype 2012}}chain]], which ordinary associative arrays do not have.
 
JavaScript has several kinds of built-in objects, namely <code>Array</code>, <code>Boolean</code>, <code>Date</code>, <code>Function</code>, <code>Math</code>, <code>Number</code>, <code>Object</code>, <code>RegExp</code> and <code>String</code>. 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.).
Line 1,589 ⟶ 1,630:
When called as a method, the standard local variable ''{{mono|this}}'' is just automatically set to the object instance to the left of the "{{mono|.}}". (There are also ''{{mono|call}}'' and ''{{mono|apply}}'' methods that can set ''{{mono|this}}'' explicitly—some packages such as [[jQuery]] do unusual things with ''{{mono|this}}''.)
 
In the example below, Foo is being used as a constructor. There is nothing special about a constructor - it is just a plain function that initialisesinitializes an object. When used with the ''{{mono|new}}'' keyword, as is the norm, ''{{mono|this}}'' is set to a newly created blank object.
 
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.
Line 1,621 ⟶ 1,662:
// m1/m3/m4 a-X a-X c-X
 
foo1.m2(); // Throws an exception, because foo1.m2 doesn'tdoes not exist.
</syntaxhighlight>
 
Line 1,669 ⟶ 1,710:
y instanceof Foo; // false
// y's prototype is Object.prototype, not
// Foo.prototype, since it was initialisedinitialized with
// {} instead of new Foo.
// Even though Foo is set to y's constructor slot,
Line 1,787 ⟶ 1,828:
 
==Native functions and methods==
{{Inline hatnote|(Not related to Web browsers.)}}
 
===eval (expression) ===
Evaluates the first parameter as an expression, which can include assignment statements. Variables local to functions can be referenced by the expression. However, {{code|eval}} represents a major security risk, as it allows a bad actor to execute arbitrary code, so its use is discouraged.<ref name="deve_eval">{{cite web |title=eval() |work=MDN Web Docs |access-date=29 January 2020 |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval! |archive-date=1 April 2022 |archive-url=https://web.archive.org/web/20220401220204/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval! |url-status=live }}</ref>
<syntaxhighlight lang="nodejsrepl">
> (function foo() {
Line 1,829 ⟶ 1,868:
{{DEFAULTSORT:Javascript Syntax}}
[[Category:JavaScript|syntax]]
[[Category:Articles with example JavaScript code]]
[[Category:Programming language syntax]]