JavaScript syntax: Difference between revisions

Content deleted Content added
Fixed typo
Tags: canned edit summary Mobile edit Mobile app edit iOS app edit
Stormgaze (talk | contribs)
m added code tags to improve consistency across article
 
(145 intermediate revisions by 78 users not shown)
Line 1:
{{Short description|Set of rules defining correctly structured programs}}
{{Very long|rps=79|date=May 2019}}{{JavaScriptSidebar}}
{{Update|date=November 2020|reason=New features/versions now in JavaScript}}
{{Use dmy dates|date=April 2020}}
{{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 [[Webweb 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==
[[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>{{Citecite 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.}}
 
==Basics==
 
===Case sensitivity===
JavaScript is [[Case sensitivity|case sensitive]]. It is common to start the name of a [[Constructor (computer science)#Constructors|constructor]] with a [[CamelCase|capitalisedcapitalized]] letter, and the name of a function or variable with a lower-case letter.
 
Example:
 
<syntaxhighlight lang="javascript">
var a = 5;
console.log(a); // 5
console.log(A); // throws a ReferenceError: A is not defined
Line 25 ⟶ 30:
 
===Whitespace and semicolons===
[[Space (punctuation)|Space]]s, [[tab character|tab]]s and [[newline]]s used outside of string constants are called [[whitespace (computer science)|whitespace]]. 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 a[[Lexical techniqueanalysis#Semicolon called "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 34 ⟶ 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.<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. TheAn example given in the spec is:<ref name="inimino" />
 
<syntaxhighlight lang="javascript">
Line 49 ⟶ 55:
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">
Line 61 ⟶ 67:
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">
Line 75 ⟶ 81:
 
===Comments===
[[Comment (computer programming)|Comment]] syntax is the same as in [[C++]], and[[Swift many(programming language)|Swift]] and 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, and any value can be stored in any variable. Starting with [[ECMAScript#6th Edition - ECMAScript 2015|ES6]], the version of the language finalised in 2015, variables can be declared with <code>let</code> (for a [[block scope|block level]] variable), <code>var</code> (for a [[function scope|function level]] variable) or <code>const</code> (for an immutable one). However, while the object assigned to a <code>const</code> cannot be changed, its properties can. Before ES6, variables were declared only with a <code>var</code> statement. An identifier must start with a letter, underscore (<tt>_</tt>), or dollar sign (<tt>$</tt>); subsequent characters can also be digits (<tt>0-9</tt>). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
 
[[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 their 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 <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===
 
Variables declared with <code>var</code> are [[lexical scoping|lexically scoped]] at a [[function scope|function level]], (notwhile ones with <code>let</code> or <code>const</code> have a [[block scope|block level]] asscope. inSince C),declarations andare thisprocessed doesbefore notany dependcode onis orderexecuted, ([[forwarda declaration]]variable iscan notbe necessary):assigned ifto aand variableused isprior to being declared insidein athe functioncode.<ref>{{cite (atweb any|title=JavaScript point,Hoisting in|publisher=[[W3Schools]] any|url=https://www.w3schools.com/js/js_hoisting.asp block)|quote=In JavaScript, thena insidevariable thecan function,be thedeclared nameafter willit resolvehas tobeen that variableused. ThisIn isother equivalentwords; ina blockvariable scopingcan tobe variablesused beingbefore forwardit has been declared. at|access-date=17 theDecember top2021 of|archive-date=31 theMarch function,2022 and|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 -->
 
HoweverWith <code>var</code>, the<code>let</code>, variable value isand <code>undefinedconst</code> untilstatements, itonly isthe initialized,declaration andis [[forwardhoisted; reference]]assignments isare not possiblehoisted. 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 onlymeans thethat declarationvalues cannot be accessed before they are declared; [[forward reference]] is hoistednot 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 assignmenttypeof exception is "const x = x;", which you can try in the console. -->
 
Function statementsdeclarations, whose effect is towhich declare a variable ofand typeassign a function to it<code>!-- Function</code> andtechnically assignisn't actually a valuetype. toThey're itobjects which can be executed in a subroutine. -->, are similar to variable statements, but in addition to hoisting the declaration, they also hoist the assignment – as if the entire statement appeared at the top of the containing function – and thus forward reference is also possible: the ___location of a function statement within an enclosing function is irrelevant. This is different from a function expression being assigned to a variable in a <code>var</code>, <code>let</code>, or <code>const</code> statement.
 
So, for example,
Be sure to understand that
<syntaxhighlight lang="javascript">
var func = function() { .. } // willdeclaration NOT beis hoisted only
function func() { .. } // willdeclaration beand assignment are hoisted
</syntaxhighlight>
 
Block scoping can be produced by wrapping the entire block in a function and then executing it – this is known as the [[immediately-invoked function expression]] pattern – or by declaring the variable using the <code>let</code> keyword. <!-- Two totally slightly different things, wrapping cope in a block executes the whole code in a block, while let-or-const variables can be seen in the same block. So block-scope code, where code is executed, block-scope variables, where variables can be accessed. -->
 
===Declaration and assignment===
 
Variables declared outside anya functionscope are [[global variable|global]]. If a variable is declared in a higher scope, it can be accessed by child functionsscopes.
 
When JavaScript tries to '''resolve''' an identifier, it looks in the local function scope. If this identifier is not found, it looks in the next outer function that declared the local onescope, and so on along the ''scope chain'' until it reaches the ''global scope'' where global variables reside. If it is still not found, JavaScript will raise a <code>ReferenceError</code> exception.
 
When '''assigning''' an identifier, JavaScript goes through exactly the same process to retrieve this identifier, except that if it is not found in the ''global scope'', it will create the "variable" asin athe propertyscope ofwhere theit ''globalwas object''created.<ref>ECMA-262 5e edition clarified this confusing behavior introducingwith the notion of ''Declarative Environment Record'' and ''Object Environment Record''. With this formalism, the ''global object'' is the ''Object Environment Record'' of the global ''Lexical Environment'' (the ''global scope'').</ref> As a consequence, a variable never declared will be global, if assigned. Declaring a variable (with the keyword <code>var</code>) in the ''global codescope'' (i.e. outside of any function body (or block in the case of let/const)), assigning a never declared identifier or adding a property to the ''global object'' (usually ''window'') will also create a new global variable.
 
Note that JavaScript's ''strict mode'' forbids the assignment of an undeclared variable, which avoids global namespace pollution. Also <code>const</code>!-- cannotRemoved, beunrelated declaredto withoutthe initializationfirst statement and sentence was already stated. Delete this comment if you edit this, this is just an explanation for my big edit. -->
 
=== Examples ===
 
Here are some examples of variable declarations and scope:
<!-- Maybe in this example, function f should also have a local shadowing variable name x2 -->
 
<syntaxhighlight lang="javascript">
var xx1 = 0; // A global variable, because it is not in any function
let x2 = 0; // Also global, this time because it is not in any block
 
function f() {
var z = 'foxes', r = 'birds'; // 2 local variables
m = 'fish'; // global, because it wasn'twas not declared anywhere before
 
function child() {
Line 138 ⟶ 150:
 
child();
return xx1 + x2; // We can use xx1 and x2 here, because itthey isare global
}
 
Line 147 ⟶ 159:
 
<syntaxhighlight lang="javascript">
for (let i = 0; i < 10; i++) console.log(i);
console.log(i); // throws a ReferenceError: i is not defined
</syntaxhighlight>
 
<syntaxhighlight lang="javascript">
for (const i = 0; i < 10; i++) console.log(i); // throws a TypeError: Assignment to constant variable
 
for (const i of [1,2,3]) console.log(i); //will not raise an exception. i is not reassigned but recreated in every iteration
 
const pi; // throws a SyntaxError: Missing initializer in const declaration
Line 158 ⟶ 172:
 
==Primitive data types==
{{Main|Primitive data type}}
The JavaScript language provides six [[primitive data types]]:
The JavaScript language provides six [[primitive data type]]s:
 
* Undefined
* Null
* Number
* BigInt
* String
* Boolean
Line 170 ⟶ 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 175 ⟶ 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 186 ⟶ 203:
</syntaxhighlight>
 
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.
 
===Null===
Unlike undefined, [[Null Object pattern|null]] is often set to indicate that something has been declared, but has been defined to be empty. In a Boolean context, the value of null is considered a false value in JavaScript.
 
Note: Null is a true primitive-type within the JavaScript language, of which {{mono|null}} (note case) is the single value. As such, when performing checks that enforce type checking, the null value will not equal other false types. Surprisingly, {{mono|null}} is considered an object by {{mono|[[typeof]]}}.
 
<syntaxhighlight lang="javascript">
console.log(null == undefined); // unenforced type during check, displays true
console.log(null === undefined); // enforce type during check, displays false
console.log(typeof null === 'object'); // true
</syntaxhighlight>
 
Initially the {{mono|[[typeof]]}} {{mono|null}} result caused by sequence of a coincidences. Though nowadays there might be an explanation, as null is shown at the end of Prototype Chain when there is no inheritance anymore. It is helpful to know null has a special usage, that is the difference from other primitives.
 
===Number===
Numbers are represented in binary as [[IEEE- 754]] [[floating point]] doubles,. Although this whichformat provides an accuracy of nearly 16 [[significant digits]]. Because they are [[floating point]] numbers, they doit notcannot always exactly represent real numbers, including fractions.
 
This becomes an issue when comparing or formatting numbers. For example:
 
<syntaxhighlight lang="javascript">
console.log(0.2 + 0.1 === 0.3); // displays true as per ECMASCRIPT 6 Specificationsfalse
console.log(0.94 - 0.01); // displays 0.9299999999999999
</syntaxhighlight>
 
Line 233 ⟶ 237:
0xFF; // a hexadecimal integer equal to 255, digits represented by the ...
// ... letters A-F may be upper or lowercase
</syntaxhighlight>
 
There is also a numeric separator, {{mono|_}} (the underscore), introduced in ES2021:
 
<syntaxhighlight lang="javascript">
// Note: Wikipedia syntax does not support numeric separators yet
1_000_000_000; // Used with big numbers
1_000_000.5; // Support with decimals
1_000e1_000; // Support with exponents
 
// Support with binary, octals and hex
0b0000_0000_0101_1011;
0o0001_3520_0237_1327;
0xFFFF_FFFF_FFFF_FFFE;
 
// But users cannot 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 (does 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. Does 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 252 ⟶ 278:
These three special values correspond and behave as the [[IEEE-754]] describes them.
 
The Number constructor (used as a function), or a unary + or -, may be used to perform explicit numeric conversion:
 
<syntaxhighlight lang="javascript">
varconst myString = "123.456";
varconst myNumber1 = Number(myString);
varconst myNumber2 = +myString;
</syntaxhighlight>
 
Line 263 ⟶ 289:
 
<syntaxhighlight lang="javascript">
const myNumericWrapper = new Number(123.456);
</syntaxhighlight>
 
However, NaN is not equal to itself:
However, it's impossible to use equality operators (<code>==</code> and <code>===</code>) to determine whether a value is NaN:
 
<syntaxhighlight lang="javascript">
const nan = NaN;
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(isNaN(NaN) !== NaN); // true
console.log(nan !== nan); // true
var a = NaN;
 
var b = a;
// Users can use the isNaN methods to check for NaN
console.log(a == b); // false
console.log(isNaN("converted to NaN")); // true
console.log(isNaN(NaN)); // true
console.log(Number.isNaN("not converted")); // false
console.log(Number.isNaN(NaN)); // true
</syntaxhighlight>
 
===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>
 
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" />
 
<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>{{Citecite 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 288 ⟶ 336:
 
<syntaxhighlight lang="javascript">
varconst h = greeting.charAt(0);
</syntaxhighlight>
 
Line 294 ⟶ 342:
 
<syntaxhighlight lang="javascript">
varconst h = greeting[0];
</syntaxhighlight>
 
Line 303 ⟶ 351:
</syntaxhighlight>
 
Applying the <!-- loose -->equality operator ("==") to two strings returns true, if the strings have the same contents, which means: of the same length and containing the same sequence of characters (case is significant for alphabets). Thus:
 
<syntaxhighlight lang="javascript">
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 318 ⟶ 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>
 
The {{mono|String}} constructor creates a string object (an object wrapping a string):
It is possible to create a string using the {{mono|String}} constructor:
 
<syntaxhighlight lang="javascript">
varconst greeting = new String("Hello, World!");
</syntaxhighlight>
 
These objects have a {{mono|valueOf}} method returning the primitive string wrapped within them<!-- also works with regular strings -->:
 
<syntaxhighlight lang="javascript">
varconst s = new String("Hello !");
typeof s; // Is 'object'.
typeof s.valueOf(); // Is 'string'.
Line 340 ⟶ 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 348 ⟶ 396:
===Boolean===
 
[[JavaScript]] provides a [[Boolean data type]] with {{mono|true}} and {{mono|false}} literals. The {{mono|[[typeof]]}} operator returns the string {{mono|"boolean"}} for these [[primitive types]]. When used in a logical context, {{mono|0}}, {{mono|-0}}, {{mono|null}}, {{mono|NaN}}, {{mono|undefined}}, and the empty string ({{mono|""}}) evaluate as {{mono|false}} due to automatic [[type coercionconversion]]. All other values (the [[complement (set theory)|complement]] of the previous list) evaluate as {{mono|true}}, including the strings {{mono|"0"}}, {{mono|"false"}} and any object. 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>).
 
=== Type conversion ===
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 | accessdate=5 March 2011}}</ref>
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.
 
[[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 | accessdate=5 March 2011}}</ref>
==== 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 378 ⟶ 433:
console.log(true === !!2); // true.... data types and values match
console.log(true === !!0); // false... data types match, but values differ
console.log( 1 ? true : false); // true.... only ±0 and NaN are “falsy”"falsy" numbers
console.log("0" ? true : false); // true.... only the empty string is “falsy”"falsy"
console.log(Boolean({})); // true.... all objects are “truthy”"truthy"
</syntaxhighlight>
 
Line 386 ⟶ 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 400 ⟶ 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">
let x = Symbol(1);
const y = Symbol(1);
x === y; // => false
 
arr=[x,y];
const symbolObject = {};
arr[x]=1;
const normalObject = {};
arr[y]=2; // x and y are unique keys for the array arr
 
arr[x]; // displays 1
// since x and y are unique,
arr[y]; // displays 2
// they can be used as unique keys in an object
x=Symbol(3);
symbolObject[x] = 1;
arr; // displays [Symbol(1),Symbol(1)]
symbolObject[y] = 2;
arr[x]; // is now undefined
 
x=Symbol(1);
arrsymbolObject[x]; // undefined=> 1
symbolObject[y]; // => 2
 
// as compared to normal numeric keys
normalObject[1] = 1;
normalObject[1] = 2; // overrides the value of 1
 
normalObject[1]; // => 2
 
// changing the value of x does not change the key stored in the object
x = Symbol(3);
symbolObject[x]; // => undefined
 
// changing x back just creates another unique Symbol
x = Symbol(1);
symbolObject[x]; // => undefined
</syntaxhighlight>
 
There are also ''well known symbols''. <!-- TODO: Add table or something -->
The Symbol wrapper also provides access to a variable free iterator.
 
One of which is <code>Symbol.iterator</code>; if something implements <code>Symbol.iterator</code>, it is iterable:
 
<syntaxhighlight lang="javascript">
const x = [1, 2, 3, 4]; // x is an Array and iterable
ex=x[Symbol.iterator]() === Array.prototype[Symbol.iterator]; // providesand anArrays iteratorare for xiterable
 
while ((exv=ex.next().value)!=undefined) console.log(exv); // displays 1,2,3,4
const xIterator = x[Symbol.iterator](); // The [Symbol.iterator] function should provide an iterator for x
xIterator.next(); // { value: 1, done: false }
xIterator.next(); // { value: 2, done: false }
xIterator.next(); // { value: 3, done: false }
xIterator.next(); // { value: 4, done: false }
xIterator.next(); // { value: undefined, done: true }
xIterator.next(); // { value: undefined, done: true }
 
// for..of loops automatically iterate values
for (const value of x) {
console.log(value); // 1 2 3 4
}
 
// Sets are also iterable:
[Symbol.iterator] in Set.prototype; // true
 
for (const value of new Set(['apple', 'orange'])) {
console.log(value); // "apple" "orange"
}
</syntaxhighlight>
 
Line 433 ⟶ 524:
 
===Array===
{{Main|Array data type}}
An [[Array data type|Array]] is a JavaScript object prototyped from the <tt>Array</tt> 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, <tt>join</tt>, <tt>slice</tt>, and <tt>push</tt>).
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>).
 
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">
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>
 
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">
Line 453 ⟶ 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 460 ⟶ 552:
</syntaxhighlight>
 
Declaration of an array can use either an <ttcode>Array</ttcode> literal or the <ttcode>Array</ttcode> constructor:
 
<syntaxhighlight lang="javascript">
let myArray;
myArray = [0, 1, , , 4, 5]; // array with length 6 and 6 elements, ...
 
// ... including 2 undefined elements
// Array literals
myArray = new Array(0, 1, 2, 3, 4, 5); // array with length 6 and 6 elements
myArray = [1, 2]; // length of 2
myArray = [1, 2,]; // same array - Users can also have an extra comma at the end
 
// It 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
myArray = [0, 1, /* hole */, /* hole */, 4, 5, /* hole */,]; // length of 7
 
// With the constructor
myArray = new Array(0, 1, 2, 3, 4, 5); // length of 6
myArray = new Array(365); // an empty array with length 365
</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:
 
<syntaxhighlight lang="javascript">
const dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
Line 482 ⟶ 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 494 ⟶ 596:
===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">
Line 503 ⟶ 605:
</syntaxhighlight>
 
Methods to extract fields are provided, as well as a useful <ttcode>toString</ttcode>:
 
<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 512 ⟶ 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 518 ⟶ 620:
===Error===
 
Custom error messages can be created using the <ttcode>Error</ttcode> class:
 
<syntaxhighlight lang="javascript">
Line 527 ⟶ 629:
 
===Math===
The <tt>{{mono|Math</tt>}} object contains various math-related constants (for example, {{pi}}) and functions (for example, cosine). (Note that the <tt>{{mono|Math</tt>}} object has no constructor, unlike <tt>{{mono|Array</tt>}} or <tt>{{mono|Date</tt>}}. All its methods are "static", that is "class" methods.) All the trigonometric functions use angles expressed in [[radian]]s, not [[Degree (angle)|degrees]] or [[Grad (angle)|grads]].
 
{| class="wikitable" border="1"
|+ PropertiesSome of the constants contained in the Math object
|-
!Property!!Returned value<br />rounded to 5 digits!!Description
|-
| <tt>{{mono|Math.E</tt>}} || align=center|2.7183 || {{mvar|[[e (mathematical constant)|{{mvar|e}}]]}}: Natural logarithm base
|-
| <tt>{{mono|Math.LN2</tt>}} || align=center|0.69315 || [[Natural logarithm]] of 2
|-
| <tt>{{mono|Math.LN10</tt>}} || align=center|2.3026 || Natural logarithm of 10
|-
| <tt>{{mono|Math.LOG2E</tt>}} || align=center|1.4427 || [[Logarithm]] to the base 2 of {{mvar|e}}
|-
| <tt>{{mono|Math.LOG10E</tt>}} || align=center|0.43429 || Logarithm to the base 10 of {{mvar|e}}
|-
| <tt>{{mono|Math.PI</tt>}} || align=center|3.14159 || [[Pi|{{pi}}]]: circumference/diameter of a circle
|-
| <tt>{{mono|Math.SQRT1_2</tt>}} || align=center|0.70711 || [[Square root]] of ½
|-
| <tt>{{mono|Math.SQRT2</tt>}} || align=center|1.4142 || [[Square root of 2]]
|}
 
Line 556 ⟶ 658:
!Example!!Returned value<br />rounded to 5 digits!!Description
|-
| <tt>{{mono|Math.abs(-2.3)</tt>}} || align=center|2.3 || [[Absolute value: <tt>(x < 0) ? -x : x</tt>]]
|-
| <tt>{{mono|Math.acos(Math.SQRT1_2)</tt>}} || align=center{{val|0.78540 |ul=rad.|fmt=none}} = 45° || [[Arccosine]]
|-
| <tt>{{mono|Math.asin(Math.SQRT1_2)</tt>}} || align=center{{val|0.78540 |u=rad.|fmt=none}} = 45° || [[Arcsine]]
|-
| <tt>{{mono|Math.atan(1)</tt>}} || align=center{{val|0.78540 |u=rad.|fmt=none}} = 45° || Half circle [[arctangent]] (-{{tmath|-\pi}}/2}} to +{{tmath|+\pi}}/2}})
|-
| <tt>{{mono|Math.atan2(-3.7, -3.7)</tt>}} || align=center{{val|-2.3562 |u=rad.}} = {{val|-135°|u=deg}} || Whole circle arctangent (-{{tmath|-\pi}} to +{{tmath|+\pi}})
|-
| <tt>{{mono|Math.ceil(1.1)</tt>}} || align=center|2 || Ceiling: [[rounding|round]] up to smallest integer ≥ argument
|-
| <tt>{{mono|Math.cos(Math.PI/4)</tt><tt></tt>}} || align=center|0.70711 || [[Trigonometric functions|Cosine]]
|-
| <tt>{{mono|Math.exp</tt>(1) }}|| align=center|2.7183 || [[Exponential function]]: {{mvar|e}} raised to this power
|-
| <tt>{{mono|Math.floor(1.9)</tt>}} || align=center|1 || Floor: round down to largest integer ≤ argument
|-
| <tt>{{mono|Math.log(Math.E)</tt>}} || align=center|1 || Natural logarithm, base {{mvar|e}}
|-
| <tt>{{mono|Math.max(1, -2)</tt>}} || align=center|1 || Maximum: <tt>{{mono|(x > y) ? x : y</tt>}}
|-
| <tt>{{mono|Math.min(1, -2)</tt>}} || align=center{{val|-2}} || Minimum: <tt>{{mono|(x < y) ? x : y</tt>}}
|-
| <tt>{{mono|Math.pow(-3, 2)</tt>}} || align=center|9 || [[Exponentiation]] (raised to the power of): <tt>{{mono|Math.pow(x, y)</tt>}} gives x<sup>y</sup>
|-
| <tt>{{mono|Math.random()</tt>}} || align=center|e.g. 0.17068 || [[Pseudorandom]] number between 0 (inclusive) and 1 (exclusive)
|-
| <tt>{{mono|Math.round(1.5)</tt>}} || align=center|2 || Round to the nearest integer; half fractions are rounded up (e.g. 1.5 rounds to 2)
|-
| <tt>{{mono|Math.sin(Math.PI/4)</tt>}} || align=center|0.70711 || [[Sine]]
|-
| <tt>{{mono|Math.sqrt(49)</tt>}} || align=center|7 || Square root
|-
| <tt>{{mono|Math.tan(Math.PI/4)</tt>}} || align=center|1 || [[Trigonometric functions|Tangent]]
|}
 
Line 700 ⟶ 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>
 
===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">
// 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');
var t = add(1, 2); // => 3
console.log(t); // 3
</syntaxhighlight>
 
Line 723 ⟶ 824:
 
<syntaxhighlight lang="javascript">
varconst add = function(x, y) {
return x + y;
};
var t = add(1, 2); // => 3
console.log(t); // 3
</syntaxhighlight>
 
In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain the <code>this</code> of the global object instead of inheriting it from where it was called / what it was called on, unlike the <code>function() {}</code> expression.
There exists a shorthand for assigning a function expression to a variable, and is as follows:
 
<syntaxhighlight lang="javascript">
const add = (x, y) => {return x + y;};
// values can also be implicitly returned (i.e. no return statement is needed)
const addImplicit = (x, y) => x + y;
 
add(1, 2); // => 3
addImplicit(1, 2) // => 3
</syntaxhighlight>
 
For functions that need to be hoisted, there is a separate expression:
 
<syntaxhighlight lang="javascript">
Line 736 ⟶ 847:
return x + y;
}
var t = add(1, 2); // => 3
console.log(t); // 3
</syntaxhighlight>
 
Hoisting allows users to use the function before it is "declared":
Or
 
<syntaxhighlight lang="javascript">
var add = ((x1, y2); // => {3, not a ReferenceError
function add(x, y) {
return x + y;
});
// or
var add = ((x, y) => x + y);
 
var t = add(1, 2);
console.log(t); // 3
</syntaxhighlight>
 
A function instance has properties and methods.
 
Line 758 ⟶ 866:
}
 
console.log(subtract.length); // => 2, expectedarity of the function amount(number of arguments.)
console.log(subtract.toString());
 
Line 778 ⟶ 886:
console.log(2 + 6); // displays 8
 
// Adding a number and a string results in concatenation (from left to right)
console.log(2 + '2'); // displays 22
console.log('$' + 3 + 4); // displays $34, but $7 may have been expected
Line 784 ⟶ 892:
console.log(3 + 4 + '7'); // displays 77, numbers stay numbers until a string is added
 
// Convert a string to a number using the unary plus
console.log(+'2' === 2); // displays true
console.log(+'Hello'); // displays NaN
Line 803 ⟶ 911:
{| 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
|}
 
Line 820 ⟶ 928:
{| 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)
|}
 
<syntaxhighlight lang="javascript">
varlet x = 1;
console.log(++x); // x becomes 2; displays 2
console.log(x++); // displays 2; x becomes 3
Line 842 ⟶ 950:
 
<syntaxhighlight lang="javascript">
varconst x = 17;
console.log(x%5); // displays 2
console.log(x%6); // displays 5
Line 850 ⟶ 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>
Users could also do:
<syntaxhighlight lang="javascript">
const x = 17;
console.log(Math.abs(-x%5)); // also 3
</syntaxhighlight>
 
Line 860 ⟶ 973:
{| 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
|}
 
Line 878 ⟶ 991:
 
<syntaxhighlight lang="javascript">
varlet x = 9;
x += 1;
console.log(x); // displays: 10
Line 897 ⟶ 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 911 ⟶ 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 930 ⟶ 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 942 ⟶ 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 "<ttcode>...</ttcode>" 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, "<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>", 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 980 ⟶ 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>
 
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">
Line 993 ⟶ 1,114:
</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 <tt>...</tt> operator can only be used with <tt>Array</tt> objects. (However, there is a proposal to extend it to <tt>Object</tt>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>&gt;</ttcode> || greater than
|-
| align="center" | <ttcode>&gt;=</ttcode> || greater than or equal to
|-
| align="center" | <ttcode>&lt;</ttcode> || less than
|-
| align="center" | <ttcode>&lt;=</ttcode> || less than or equal to
|-
| align="center" | <ttcode>===</ttcode> || identical (equal and of same type)
|-
| align="center" | <ttcode>!==</ttcode> || not identical
|}
 
Line 1,020 ⟶ 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,032 ⟶ 1,151:
===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>""</tt></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">
Line 1,095 ⟶ 1,214:
</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">
Line 1,113 ⟶ 1,232:
 
<syntaxhighlight lang="javascript">
varconst s = t || "(default)"; // assigns t, or the default value, if t is null, empty, etc.
</syntaxhighlight>
 
===Bitwise Logical assignment ===
{| class="wikitable"
{{Expand section|date=April 2011}}
|-
| align="center" | <code>??=</code>
| Nullish assignment
|-
| align="center" | <code><nowiki>||=</nowiki></code>
| Logical Or assignment
|-
| align="center" | <code>&&=</code>
| Logical And assignment
|}
 
=== Bitwise ===
JavaScript supports the following '''binary [[Bitwise operation|bitwise operators]]''':
 
{| class="wikitable"
|-
| align="center" | <ttcode>&</ttcode> || AND
|-
| align="center" | <ttcode>|</ttcode> || OR
|-
| align="center" | <ttcode>^</ttcode> || XOR
|-
| align="center" | <code>!</code> || NOT
|!
|NOT
|-
| align="center" | <ttcode>&lt;&lt;</ttcode> || shift left (zero fill at right)
|-
| align="center" | <ttcode>&gt;&gt;</ttcode> || shift right (sign-propagating); copies of the<br />leftmost bit (sign bit) are shifted in from the left
|-
| align="center" | <ttcode>&gt;&gt;&gt;</ttcode> || shift right (zero fill at left). For positive numbers,<br /><ttcode>&gt;&gt;</ttcode> and <ttcode>&gt;&gt;&gt;</ttcode> yield the same result.
|}
 
Line 1,141 ⟶ 1,271:
 
<syntaxhighlight lang="javascript">
const x = 11 & 6;
console.log(x); // 2
</syntaxhighlight>
Line 1,149 ⟶ 1,279:
{| class="wikitable"
|-
| align="center" | <ttcode>~</ttcode> || NOT (inverts the bits)
|}
 
Line 1,158 ⟶ 1,288:
{| class="wikitable"
|-
| align="center" | <ttcode>&=</ttcode> || and
|-
| align="center" | <ttcode>|=</ttcode> || or
|-
| align="center" | <ttcode>^=</ttcode> || xor
|-
| align="center" | <ttcode>&lt;&lt;=</ttcode> || shift left (zero fill at right)
|-
| align="center" | <ttcode>&gt;&gt;=</ttcode> || shift right (sign-propagating); copies of the<br />leftmost bit (sign bit) are shifted in from the left
|-
| align="center" | <ttcode>&gt;&gt;&gt;=</ttcode> || shift right (zero fill at left). For positive numbers,<br /><ttcode>&gt;&gt;=</ttcode> and <ttcode>&gt;&gt;&gt;=</ttcode> yield the same result.
|}
 
Line 1,174 ⟶ 1,304:
 
<syntaxhighlight lang="javascript">
let x=7;
console.log(x); // 7
x<<=3;
Line 1,184 ⟶ 1,314:
{| class="wikitable"
|-
| align="center" | <ttcode>=</ttcode> || assignment
|-
| align="center" | <ttcode>+</ttcode> || concatenation
|-
| align="center" | <ttcode>+=</ttcode> || concatenate and assign
|}
 
Line 1,194 ⟶ 1,324:
 
<syntaxhighlight lang="javascript">
let str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
 
const str2 = "2" + 2; // "22", not "4" or 4.
</syntaxhighlight>
 
===??===
{{excerpt|Null coalescing operator|JavaScript}}
 
==Control structures==
Line 1,204 ⟶ 1,337:
===Compound statements===
 
A pair of curly brackets <ttcode>{&nbsp;}</ttcode> and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
 
===If ... else===
Line 1,222 ⟶ 1,355:
 
<syntaxhighlight lang="javascript">
const result = condition ? expression : alternative;
</syntaxhighlight>
 
Line 1,228 ⟶ 1,361:
 
<syntaxhighlight lang="javascript">
if (condition) {
const result = expression;
} else {
const result = alternative;
}
</syntaxhighlight>
 
Line 1,246 ⟶ 1,379:
break;
case ANOTHERVALUE:
// statements for when ANOTHERVALUE || ORNAOTHERONE
// no break statement, falling through to the following case
case ORANOTHERONE:
// statements specific to ORANOTHERONE (i.e. !ANOTHERVALUE && ORANOTHER);
break; //The buck stops here.
case YETANOTHER:
// statements;
break;
Line 1,254 ⟶ 1,393:
</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. This ''fall through'' behavior can be used when the same set of statements apply in several cases, effectively creating a [[disjunction]] between those cases.
* 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.
Line 1,281 ⟶ 1,420:
 
===For ... in loop===
The syntax of the JavaScript <code>[[Foreach loop|for ... in loop]]</code> is as follows:
 
<syntaxhighlight lang="javascript">
Line 1,291 ⟶ 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,322 ⟶ 1,461:
<syntaxhighlight lang="javascript">
with (document) {
varconst a = getElementById('a');
varconst b = getElementById('b');
varconst c = getElementById('c');
};
</syntaxhighlight>
Line 1,334 ⟶ 1,473:
 
===Labels===
JavaScript supports nested labels in most implementations. Loops or blocks can be labelledlabeled 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">
loop1: for (varlet a = 0; a < 10; a++a) {
if (a === 4) {break loop1; // Stops after the 4th attempt
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 loop2loop1; // NumberContinues 3the first loop, 'finished' is skippednot shown
}
if (b == 6) {
continue loop1; // Continues the first loop, 'finished' is not shown
}
console.log('b = ' + b);
} //end of loop2
}
console.log('finished');
} //end of loop1
}
block1: {
console.log('Hello'); // Displays 'Hello'
Line 1,362 ⟶ 1,495:
 
==Functions==
{{Main|Function (computer programming)}}
 
A [[functionFunction (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 user exitexits the function without a return statement, the value {{mono|undefined}} is returned.
 
<syntaxhighlight lang="javascript+genshitext">
function gcd(segmentAnumber1, segmentBnumber2) {
if (isNaN(number1*number2)) throw TypeError("Non-Numeric arguments not allowed.");
var diff = segmentA - segmentB;
number1 = Math.round(number1);
if (diff == 0)
number2 = Math.round(number2);
return segmentA;
let difference = number1 - number2;
return diff > 0 ? gcd(segmentB, diff) : gcd(segmentA, -diff);
if (difference === 0) return number1;
return difference > 0 ? gcd(number2, difference) : gcd(number1, -difference);
}
console.log(gcd(60, 40)); // 20
 
//In the absence of parentheses following the identifier 'gcd' on the RHS of the assignment below,
var mygcd = gcd; // mygcd is a reference to the same function as gcd. Note no argument ()s.
//'gcd' returns a reference to the function itself without invoking it.
let mygcd = gcd; // mygcd and gcd reference the same function.
console.log(mygcd(60, 40)); // 20
</syntaxhighlight>
Line 1,380 ⟶ 1,518:
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">
Line 1,396 ⟶ 1,534:
 
<syntaxhighlight lang="javascript">
varconst obj1 = {a : 1};
varconst obj2 = {b : 2};
function foo(p) {
p = obj2; // Ignores actual parameter
Line 1,403 ⟶ 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,409 ⟶ 1,547:
 
<syntaxhighlight lang="javascript">
varlet vt = "Top";
varlet bar, baz;
function foo() {
varlet vf = "fudfoo var";
bar = function() { console.log(vf) };
baz = function(x) { vf = x; };
}
foo();
baz("Fuglybaz arg");
bar(); // Fugly"baz arg" (not fud"foo var") even though foo() has exited.
console.log(vt); // 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===
{{excerpt|Async/await|In JavaScript}}
 
==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 <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===
Line 1,432 ⟶ 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,445 ⟶ 1,613:
 
<syntaxhighlight lang="javascript">
varconst myStructure = {
name: {
first: "Mel",
Line 1,458 ⟶ 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,480 ⟶ 1,648:
}
 
varconst foo1 = new Foo(1);
varconst foo2 = new Foo(0);
foo2.prefix = "b-";
 
Line 1,488 ⟶ 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,494 ⟶ 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,512 ⟶ 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,523 ⟶ 1,691:
console.log(object.attributeB); // undefined
 
delete object; // remove the whole Object (rarely used)
console.log(object.attributeA); // throws an exception
</syntaxhighlight>
 
Line 1,534 ⟶ 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,551 ⟶ 1,717:
</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.
Line 1,576 ⟶ 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,603 ⟶ 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,662 ⟶ 1,828:
 
==Native functions and methods==
{{Inline hatnote|(Not related to Web browsers.)}}
 
===eval (expression) ===
Evaluates expressionthe stringfirst parameter as an expression, which can include assignment statements. Variables local to functions can be referenced by the expression. However, the {{code|eval}} represents a major security risk, as it allows a bad actor to execute arbitrary code, and so its use is discouraged.<ref name="deve_eval">{{Citecite 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="javascriptnodejsrepl">
> (function foo() {
... var x = 7;
... console.log("val " + eval("x + 2"));
... })();
})(); // shows val 9.
val 9
undefined
</syntaxhighlight>
 
Line 1,678 ⟶ 1,844:
 
==References==
{{Reflist}}
<references />
 
==Further reading==
Line 1,693 ⟶ 1,859:
* ECMAScript standard references: [http://www.ecma-international.org/publications/standards/Ecma-262.htm ECMA-262]
* [https://web.archive.org/web/20120527095306/http://javalessons.com/cgi-bin/fun/java-tutorials-main.cgi?sub=javascript&code=script Interactive JavaScript Lessons - example-based]
* [http://javascript.about.com/ JavaScript on About.com: lessons and explanation] {{Webarchive|url=https://web.archive.org/web/20170225135310/http://javascript.about.com/ |date=25 February 2017 }}
* [https://web.archive.org/web/20150110202627/http://wisentechnologies.com/it-courses/JavaScript-Training-in-Chennai.aspx JavaScript Training]
* Mozilla Developer Center Core References for JavaScript versions [https://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference 1.5], [https://web.archive.org/web/20070210000908/http://research.nihonsoft.org/javascript/CoreReferenceJS14/index.html 1.4], [https://web.archive.org/web/20070210000504/http://research.nihonsoft.org/javascript/ClientReferenceJS13/index.html 1.3] and [https://web.archive.org/web/20070210000545/http://research.nihonsoft.org/javascript/jsref/index.htm 1.2]
Line 1,702 ⟶ 1,868:
{{DEFAULTSORT:Javascript Syntax}}
[[Category:JavaScript|syntax]]
[[Category:Articles with example JavaScript code]]
[[Category:Programming language syntax]]