JavaScript syntax: Difference between revisions

Content deleted Content added
Stormgaze (talk | contribs)
m added code tags to improve consistency across article
 
(66 intermediate revisions by 33 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
}}
{{Use dmy dates|date=April 2022}}
{{Use American English|date=April 2025}}
 
[[File:Source code in Javascript.png|thumb|A snippet of [[JavaScript]] 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 syntax in the first paragraph of the 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|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.}}
 
Line 18 ⟶ 19:
 
===Case sensitivity===
JavaScript is [[Case sensitivity|case sensitive]]. It is common to start the name of a [[JavaScript syntax#Constructors|constructor]] with a [[CamelCase|capitalisedcapitalized]] letter, and the name of a function or variable with a lower-case letter.
 
Example:
Line 29 ⟶ 30:
 
===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 38 ⟶ 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 79 ⟶ 81:
 
===Comments===
[[Comment (computer programming)|Comment]] syntax is the same as in [[C++]], [[Swift (programming language)|Swift]] and many other programming 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>
 
==Variables==
{{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 its properties can. 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".
 
[[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 |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=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 98 ⟶ 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 132 ⟶ 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 165 ⟶ 172:
 
==Primitive data types==
{{Main|Primitive data type}}
The JavaScript language provides six [[primitive data type]]s:
 
Line 177 ⟶ 185:
 
===Undefined===
{{Main|Undefined value}}
 
The [[undefined value|value of "undefined"]] is assigned to all [[uninitialized variable]]s, and is also returned when checking for object properties that do not exist. In a Boolean context, the undefined value is considered a false value.
 
Line 182 ⟶ 192:
 
<syntaxhighlight lang="javascript">
varlet test; // variable declared, but not defined, ...
// ... set to value of undefined
varconst testObj = {};
console.log(test); // test variable exists, but value not ...
// ... defined, displays undefined
Line 195 ⟶ 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">
function isUndefined(x) { varlet u; return x === u; } // like this...
function isUndefined(x) { return x === void 0; } // ... or that second one
function isUndefined(x) { return (typeof x) === "undefined"; } // ... or that third one
</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 229 ⟶ 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 242 ⟶ 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 271 ⟶ 281:
 
<syntaxhighlight lang="javascript">
varconst myString = "123.456";
varconst myNumber1 = Number(myString);
varconst myNumber2 = +myString;
</syntaxhighlight>
 
Line 279 ⟶ 289:
 
<syntaxhighlight lang="javascript">
const myNumericWrapper = new Number(123.456);
</syntaxhighlight>
 
Line 291 ⟶ 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 299 ⟶ 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">
varconst greeting = "Hello, World!";
varconst 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 314 ⟶ 336:
 
<syntaxhighlight lang="javascript">
varconst h = greeting.charAt(0);
</syntaxhighlight>
 
Line 320 ⟶ 342:
 
<syntaxhighlight lang="javascript">
varconst h = greeting[0];
</syntaxhighlight>
 
Line 332 ⟶ 354:
 
<syntaxhighlight lang="javascript">
varconst x = "World";
varconst compare1 = ("Hello, " + x == "Hello, World"); // Here compare1 contains true.
varconst compare2 = ("Hello, " + x == "hello, World"); // Here compare2 contains ...
// ... false since the ...
// ... first characters ...
// ... of both operands ...
// ... are not of the same case.
</syntaxhighlight>
 
Line 344 ⟶ 366:
 
<syntaxhighlight lang="javascript">
varlet x = '"Hello, World!" he said.'; // Just fine.
var x = ""Hello, World!" he said."; // Not good.
var x = "\"Hello, World!\" he said."; // Works by escaping " with \"
</syntaxhighlight>
 
Line 352 ⟶ 374:
 
<syntaxhighlight lang="javascript">
varconst greeting = new String("Hello, World!");
</syntaxhighlight>
 
Line 358 ⟶ 380:
 
<syntaxhighlight lang="javascript">
varconst s = new String("Hello !");
typeof s; // Is 'object'.
typeof s.valueOf(); // Is 'string'.
Line 366 ⟶ 388:
 
<syntaxhighlight lang="javascript">
varconst s1 = new String("Hello !");
varconst s2 = new String("Hello !");
s1 == s2; // Is false, because they are two distinct objects.
s1.valueOf() == s2.valueOf(); // Is true.
Line 379 ⟶ 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 416 ⟶ 441:
 
<syntaxhighlight lang="javascript">
varconst b = new Boolean(false); // Object false {}
varconst t = Boolean(b); // Boolean true
varconst f = Boolean(b.valueOf()); // Boolean false
varlet n = new Boolean(b); // Not recommended
n = new Boolean(b.valueOf()); // Preferred
 
Line 430 ⟶ 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:
 
<syntaxhighlight lang="javascript">
varlet x = Symbol(1);
varconst y = Symbol(1);
x === y; // => false
 
varconst symbolObject = {};
varconst normalObject = {};
 
// since x and y are unique,
Line 467 ⟶ 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">
letconst x = [1, 2, 3, 4]; // x is an Array
x[Symbol.iterator] === Array.prototype[Symbol.iterator]; // and Arrays are iterable
 
Line 499 ⟶ 524:
 
===Array===
{{Main|Array data type}}
An [[Array data type|Array]] is a JavaScript object prototyped from the <code>Array</code> 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, <code>join</code>, <code>slice</code>, and <code>push</code>).
 
Line 504 ⟶ 530:
 
<syntaxhighlight lang="javascript">
varconst myArray = []; // Point the variable myArray to a newly ...
// ... created, empty Array
myArray.push("hello World"); // Fill the next empty index, in this case 0
console.log(myArray[0]); // Equivalent to console.log("hello World");
</syntaxhighlight>
 
Line 519 ⟶ 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 533 ⟶ 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 550 ⟶ 576:
 
<syntaxhighlight lang="javascript">
const dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
Line 558 ⟶ 584:
 
<syntaxhighlight lang="javascript">
const cats = [{color: "brown", size: "large"},
{color: "black", size: "small"}];
cats[0]["size"]; // results in "large"
 
const dogs = {rover: {color: "brown", size: "large"},
spot: {color: "black", size: "small"}};
dogs["spot"]["size"]; // results in "small"
Line 574 ⟶ 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 582 ⟶ 608:
 
<syntaxhighlight lang="javascript">
varconst d = new Date(2010, 2, 1, 14, 25, 30); // 2010-Mar-01 14:25:30;
 
// Displays '2010-3-1 14:25:30':
Line 588 ⟶ 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 646 ⟶ 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 776 ⟶ 802:
====Capturing groups====
<syntaxhighlight lang="javascript">
varconst myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;
varconst results = myRe.exec("The date and time are 2009-09-08 09:37:08.");
if (results) {
console.log("Matched: " + results[0]); // Entire match
varconst my_date = results[1]; // First group == "2009-09-08"
varconst my_time = results[2]; // Second group == "09:37:08"
console.log("`It is " + ${my_time + "} on " + ${my_date}`);
} else console.log("Did not find a valid date!");
</syntaxhighlight>
Line 791 ⟶ 817:
<syntaxhighlight lang="javascript">
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
varconst add = new Function('x', 'y', 'return x + y');
add(1, 2); // => 3
</syntaxhighlight>
Line 798 ⟶ 824:
 
<syntaxhighlight lang="javascript">
varconst add = function(x, y) {
return x + y;
};
Line 807 ⟶ 833:
 
<syntaxhighlight lang="javascript">
varconst add = (x, y) => {return x + y;};
// values can also be implicitly returned (i.e. no return statement is needed)
varconst addImplicit = (x, y) => x + y;
 
add(1, 2); // => 3
Line 824 ⟶ 850:
</syntaxhighlight>
 
Hoisting allows youusers to use the function before it is "declared":
 
<syntaxhighlight lang="javascript">
Line 912 ⟶ 938:
 
<syntaxhighlight lang="javascript">
varlet x = 1;
console.log(++x); // x becomes 2; displays 2
console.log(x++); // displays 2; x becomes 3
Line 924 ⟶ 950:
 
<syntaxhighlight lang="javascript">
varconst x = 17;
console.log(x%5); // displays 2
console.log(x%6); // displays 5
Line 932 ⟶ 958:
</syntaxhighlight>
 
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again:
 
<syntaxhighlight lang="javascript">
varconst x = 17;
console.log((-x%5+5)%5); // displays 3
</syntaxhighlight>
YouUsers could also do:
<syntaxhighlight lang="javascript">
varconst x = 17;
console.log(Math.abs(-x%5)); // also 3
</syntaxhighlight>
Line 965 ⟶ 991:
 
<syntaxhighlight lang="javascript">
varlet x = 9;
x += 1;
console.log(x); // displays: 10
Line 984 ⟶ 1,010:
* To learn JavaScript objects...
*/
varconst object_1 = {a: 1}; // assign reference of newly created object to object_1
varlet object_2 = {a: 0};
varlet object_3 = object_2; // object_3 references the same object as object_2 does
object_3.a = 2;
Line 998 ⟶ 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,017 ⟶ 1,043:
 
<syntaxhighlight lang="javascript">
varlet a, b, c, d, e;
[a, b, c] = [3, 4, 5];
console.log(`${a + '},' + ${b + '},' + ${c}`); // displays: 3,4,5
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
varconst 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
console.log(a + ',' + b); // displays: 6,5
Line 1,029 ⟶ 1,055:
[a, b, c] = [3, 4, 5]; // permutations
[a, b, c] = [b, c, a];
console.log(`${a + '},' + ${b + '},' + ${c}`); // displays: 4,5,3
</syntaxhighlight>
 
==== 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">
varconst a = [1, 2, 3, 4];
 
// It can be used multiple times in the same expression
varconst b = [...a, ...a]; // b = [1, 2, 3, 4, 1, 2, 3, 4];
 
// It can be combined with non-spread items.
varconst c = [5, 6, ...a, 7, 9]; // c = [5, 6, 1, 2, 3, 4, 7, 9];
 
// For comparison, doing this without the spread operator
// creates a nested array.
varconst d = [a, a]; // d = [[1, 2, 3, 4], [1, 2, 3, 4]]
 
// It works the same with function calls
function foo(arg1, arg2, arg3) {
console.log(`${arg1 + '}:' + ${arg2 + '}:' + ${arg3}`);
}
 
// 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,067 ⟶ 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,081 ⟶ 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,107 ⟶ 1,139:
 
<syntaxhighlight lang="javascript">
varconst obj1 = {a: 1};
varconst obj2 = {a: 1};
varconst obj3 = obj1;
console.log(obj1 == obj2); //false
console.log(obj3 == obj1); //true
Line 1,200 ⟶ 1,232:
 
<syntaxhighlight lang="javascript">
varconst s = t || "(default)"; // assigns t, or the default value, if t is null, empty, etc.
</syntaxhighlight>
 
Line 1,217 ⟶ 1,249:
 
=== Bitwise ===
{{Expand section|date=April 2011}}
JavaScript supports the following '''binary [[Bitwise operation|bitwise operators]]''':
 
Line 1,228 ⟶ 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,241 ⟶ 1,271:
 
<syntaxhighlight lang="javascript">
const x = 11 & 6;
console.log(x); // 2
</syntaxhighlight>
Line 1,274 ⟶ 1,304:
 
<syntaxhighlight lang="javascript">
let x=7;
console.log(x); // 7
x<<=3;
Line 1,294 ⟶ 1,324:
 
<syntaxhighlight lang="javascript">
let str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
 
const str2 = "2" + 2; // "22", not "4" or 4.
</syntaxhighlight>
 
Line 1,325 ⟶ 1,355:
 
<syntaxhighlight lang="javascript">
const result = condition ? expression : alternative;
</syntaxhighlight>
 
Line 1,331 ⟶ 1,361:
 
<syntaxhighlight lang="javascript">
if (condition) {
const result = expression;
} else {
const result = alternative;
}
</syntaxhighlight>
 
Line 1,400 ⟶ 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,431 ⟶ 1,461:
<syntaxhighlight lang="javascript">
with (document) {
varconst a = getElementById('a');
varconst b = getElementById('b');
varconst c = getElementById('c');
};
</syntaxhighlight>
Line 1,443 ⟶ 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">
loop1: for (varlet a = 0; a < 10; ++a) {
if (a === 4) break loop1; // Stops after the 4th attempt
console.log('a = ' + a);
loop2: for (varlet b = 0; b < 10; ++b) {
if (b === 3) continue loop2; // Number 3 is skipped
if (b === 6) continue loop1; // Continues the first loop, 'finished' is not shown
Line 1,465 ⟶ 1,495:
 
==Functions==
{{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,503 ⟶ 1,534:
 
<syntaxhighlight lang="javascript">
varconst obj1 = {a : 1};
varconst obj2 = {b : 2};
function foo(p) {
p = obj2; // Ignores actual parameter
Line 1,510 ⟶ 1,541:
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
console.log(`${obj1.a} + " " + ${obj2.b}`); // writes 1 3
</syntaxhighlight>
 
Line 1,528 ⟶ 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,533 ⟶ 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,542 ⟶ 1,600:
<syntaxhighlight lang="javascript">
// Constructor
varconst anObject = new Object();
 
// Object literal
varconst objectA = {};
varconst objectA2 = {}; // A != A2, {}s create new objects as copies.
varconst objectB = {index1: 'value 1', index2: 'value 2'};
 
// Custom constructor (see below)
Line 1,555 ⟶ 1,613:
 
<syntaxhighlight lang="javascript">
varconst myStructure = {
name: {
first: "Mel",
Line 1,568 ⟶ 1,626:
===Methods===
 
A [[methodMethod (computer scienceprogramming)|method]] is simply a function that has been assigned to a property name of an object. Unlike many object-oriented languages, there is no distinction between a function definition and a method definition in object-related JavaScript. Rather, the distinction occurs during function calling; a function can be called as a method.
 
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,590 ⟶ 1,648:
}
 
varconst foo1 = new Foo(1);
varconst foo2 = new Foo(0);
foo2.prefix = "b-";
 
Line 1,598 ⟶ 1,656:
 
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px()
varconst baz = {"prefix": "c-"};
baz.m4 = px; // No need for a constructor to make an object.
 
Line 1,604 ⟶ 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,622 ⟶ 1,680:
console.log(MyObject.staticC); // blue
 
const object = new MyObject('red', 1000);
 
console.log(object.attributeA); // red
console.log(object[".attributeB"]); // 1000
 
console.log(object.staticC); // undefined
Line 1,642 ⟶ 1,700:
// x = new Foo() would set x's prototype to Foo.prototype,
// and Foo.prototype has a constructor slot pointing back to Foo).
const x = new Foo();
// The above is almost equivalent to
const y = {};
y.constructor = Foo;
y.constructor();
// Except
x.constructor == y.constructor; // true
x instanceof Foo; // true
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,684 ⟶ 1,742:
}
 
const base = new Base();
Derived.prototype = base; // Must be before new Derived()
Derived.prototype.constructor = Derived; // Required to make `instanceof` work
 
const d = new Derived(); // Copies Derived.prototype to d instance's hidden prototype slot.
d instanceof Derived; // true
d instanceof Base; // true
 
base.aBaseFunction = function() { console.log("Base::aNEWBaseFunction()"); };
 
d.anOverride(); // Derived::anOverride()
Line 1,711 ⟶ 1,769:
 
Base.prototype.m = m2;
const bar = new Base();
console.log("bar.m " + bar.m()); // bar.m Two
 
function Top() { this.m = m3; }
const t = new Top();
 
const foo = new Base();
Base.prototype = t;
// No effect on foo, the *reference* to t is copied.
console.log("foo.m " + foo.m()); // foo.m Two
 
const baz = new Base();
console.log("baz.m " + baz.m()); // baz.m Three
 
Line 1,770 ⟶ 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,812 ⟶ 1,868:
{{DEFAULTSORT:Javascript Syntax}}
[[Category:JavaScript|syntax]]
[[Category:Articles with example JavaScript code]]
[[Category:Programming language syntax]]