JavaScript syntax: Difference between revisions
Chanced upon this; the TA is wrong here and this is a very big WP:NOTHOWTO Tags: New redirect Manual revert Reverted Visual edit |
m Reverted edit by ~2026-56933-19 (talk) to last version by Voidxor |
||
| (34 intermediate revisions by 23 users not shown) | |||
| Line 1: | Line 1: | ||
{{Short description|Set of rules defining correctly structured programs}} |
|||
#REDIRECT [[JavaScript]] |
|||
{{Update|date=November 2020|reason=Rewrite the article to be less tutorial-like and more primarily focused on syntax/features}} |
|||
{{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 of JavaScript''' is the [[Syntax (programming languages)|set of rules]] that define a correctly structured [[JavaScript]] program. |
|||
The examples below make use of the <code>console.log()</code> function 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 it is not commonly used. |
|||
[[TypeScript]], which extends JavaScript with type annotations and additional features, has the same syntax as well as its own additional features. |
|||
==Origins== |
|||
[[File:JavaScript code.png|thumb|JavaScript code which displays weekdays in a browser]] |
|||
[[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=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: |
|||
{{Blockquote|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.}} |
|||
JavaScript syntax is mostly derived from [[Java syntax]], which in turn is derived from [[C syntax]] and [[C++ syntax]]. |
|||
==Basics== |
|||
===Keywords=== |
|||
====Reserved keywords==== |
|||
The following words are keywords: |
|||
{{div col|colwidth=15em}} |
|||
* <code>break</code> |
|||
* <code>case</code> |
|||
* <code>catch</code> |
|||
* <code>class</code> |
|||
* <code>const</code> |
|||
* <code>continue</code> |
|||
* <code>debugger</code> |
|||
* <code>default</code> |
|||
* <code>delete</code> |
|||
* <code>do</code> |
|||
* <code>else</code> |
|||
* <code>enum</code> |
|||
* <code>eval</code> |
|||
* <code>export</code> |
|||
* <code>extends</code> |
|||
* <code>finally</code> |
|||
* <code>for</code> |
|||
* <code>function</code> |
|||
* <code>if</code> |
|||
* <code>import</code> |
|||
* <code>in</code> |
|||
* <code>instanceof</code> |
|||
* <code>new</code> |
|||
* <code>return</code> |
|||
* <code>super</code> |
|||
* <code>switch</code> |
|||
* <code>this</code> |
|||
* <code>throw</code> |
|||
* <code>try</code> |
|||
* <code>typeof</code> |
|||
* <code>using</code> |
|||
* <code>var</code> |
|||
* <code>void</code> |
|||
* <code>while</code> |
|||
* <code>with</code> |
|||
{{div col end}} |
|||
====Reserved keywords in strict mode==== |
|||
The following words are keywords in strict mode: |
|||
{{div col|colwidth=15em}} |
|||
* <code>let</code> |
|||
* <code>implements</code> |
|||
* <code>interface</code> |
|||
* <code>static</code> |
|||
* <code>package</code> |
|||
* <code>private</code> |
|||
* <code>protected</code> |
|||
* <code>public</code> |
|||
* <code>yield</code> |
|||
{{div col end}} |
|||
====Reserved keywords in module code or async function body==== |
|||
The following words are keywords in module code or async function body: |
|||
{{div col|colwidth=15em}} |
|||
* <code>await</code> |
|||
{{div col end}} |
|||
====Literal values==== |
|||
The following words refer to literal values used by the language: |
|||
{{div col|colwidth=15em}} |
|||
* <code>true</code> |
|||
* <code>false</code> |
|||
* <code>null</code> |
|||
{{div col end}} |
|||
JavaScript also defines the following global constants, which are not keywords: |
|||
{{div col|colwidth=15em}} |
|||
* <code>NaN</code> |
|||
* <code>Infinity</code> |
|||
* <code>undefined</code> |
|||
{{div col end}} |
|||
====Removed keywords==== |
|||
The following words, primarily associated with Java, were removed from the [[ECMAScript]] 5/6 standard: |
|||
{{div col|colwidth=15em}} |
|||
* <code>abstract</code> |
|||
* <code>boolean</code> |
|||
* <code>byte</code> |
|||
* <code>char</code> |
|||
* <code>double</code> |
|||
* <code>final</code> |
|||
* <code>float</code> |
|||
* <code>goto</code> |
|||
* <code>int</code> |
|||
* <code>long</code> |
|||
* <code>native</code> |
|||
* <code>short</code> |
|||
* <code>synchronized</code> |
|||
* <code>throws</code> |
|||
* <code>transient</code> |
|||
* <code>volatile</code> |
|||
{{div col end}} |
|||
====TypeScript keywords==== |
|||
The additional following words are keywords in TypeScript: |
|||
{{div col|colwidth=15em}} |
|||
* <code>abstract</code> |
|||
* <code>any</code> |
|||
* <code>as</code> |
|||
* <code>declare</code> |
|||
* <code>infer</code> |
|||
* <code>keyof</code> |
|||
* <code>module</code> |
|||
* <code>namespace</code> |
|||
* <code>never</code> |
|||
* <code>readonly</code> |
|||
* <code>type</code> |
|||
* <code>unknown</code> |
|||
{{div col end}} |
|||
===Case sensitivity=== |
|||
JavaScript is [[Case sensitivity|case sensitive]]. It is common to start the name of a [[#Constructors|constructor]] with a [[CamelCase|capitalized]] 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 |
|||
</syntaxhighlight> |
|||
===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 |
|||
|url-access=registration |
|||
|last=Flanagan |
|||
|first=David |
|||
|page=[https://archive.org/details/javascript00libg_297/page/n14 16] |
|||
|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|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. |
|||
The five problematic tokens are the open parenthesis "<code>(</code>", open bracket "<code>[</code>", slash "<code>/</code>", plus "<code>+</code>", and minus "<code>-</code>". Of these, the open parenthesis is common in the [[immediately invoked function expression]] pattern, and open bracket occurs sometimes, while others are quite rare. An example: |
|||
<syntaxhighlight lang="javascript"> |
|||
a = b + c |
|||
(d + e).foo() |
|||
// Treated as: |
|||
// a = b + c(d + e).foo(); |
|||
</syntaxhighlight> |
|||
with the suggestion that the preceding statement be terminated with a semicolon. |
|||
Some suggest instead the use of ''leading'' semicolons on lines starting with '<code>(</code>' or '<code><nowiki>[</nowiki></code>', so the line is not accidentally joined with the previous one. This is known as a '''defensive semicolon''', and is employed because code may otherwise become ambiguous when it is rearranged. For example: |
|||
<syntaxhighlight lang="javascript"> |
|||
a = b + c |
|||
;(d + e).foo() |
|||
// Treated as: |
|||
// a = b + c; |
|||
// (d + e).foo(); |
|||
</syntaxhighlight> |
|||
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. In such a case where perhaps unusual semicolon placement occurs, it may just be better to manually place semicolons at the end of statements. |
|||
The five restricted productions are <code>return</code>, <code>throw</code>, <code>break</code>, <code>continue</code>, 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. <code>return</code> and <code>throw</code> take an optional value, while <code>break</code> and <code>continue</code> take an optional label. In all cases, the advice is to keep the value or label on the same line as the statement. This most often shows up in the return statement, where one might return a large object literal, which might be accidentally placed starting on a new line. For post-increment/decrement, there is potential ambiguity with pre-increment/decrement, and again it is recommended to simply keep these on the same line. |
|||
<syntaxhighlight lang="javascript"> |
|||
return |
|||
a + b; |
|||
// Returns undefined. Treated as: |
|||
// return; |
|||
// a + b; |
|||
// Should be written as: |
|||
// return a + b; |
|||
</syntaxhighlight> |
|||
===Comments=== |
|||
[[Comment (computer programming)|Comment]] syntax is the same as in [[C (programming language)|C]], [[C++]] and other programming languages. |
|||
Single-line comments begin with <code>//</code> and continue until the end of the line. Multi-line comments start with <code>/*</code> and end with <code>*/</code> , and can span multiple lines. |
|||
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"> |
|||
#! Hashbang comment |
|||
// One-line comment |
|||
/* Multi-line |
|||
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 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 "{{mono|A}}" through "{{mono|Z}}" are different from the lowercase characters "{{mono|a}}" through "{{mono|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]] ({{mono|@}}) 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]], 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</ref> |
|||
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. |
|||
Function declarations, which declare a variable and assign a function to it, 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, |
|||
<syntaxhighlight lang="javascript"> |
|||
var func = function() { .. } // declaration is hoisted only |
|||
function func() { .. } // declaration and 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 a scope are [[global variable|global]]. If a variable is declared in a higher scope, it can be accessed by child scopes. |
|||
When JavaScript tries to '''resolve''' an identifier, it looks in the local scope. If this identifier is not found, it looks in the next outer scope, 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" in the scope where it was created.<ref>ECMA-262 5e edition clarified this behavior with the ''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 scope'' (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. <!-- Removed, unrelated to the first 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 x1 = 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 was not declared anywhere before |
|||
function child() { |
|||
var r = 'monkeys'; // This variable is local and does not affect the "birds" r of the parent function. |
|||
z = 'penguins'; // Closure: Child function is able to access the variables of the parent function. |
|||
} |
|||
twenty = 20; // This variable is declared on the next line, but usable anywhere in the function, even before, as here |
|||
var twenty; |
|||
child(); |
|||
return x1 + x2; // We can use x1 and x2 here, because they are global |
|||
} |
|||
f(); |
|||
console.log(z); // This line will raise a ReferenceError exception, because the value of z is no longer available |
|||
</syntaxhighlight> |
|||
<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 |
|||
</syntaxhighlight> |
|||
==Primitive data types== |
|||
{{Main|Primitive data type}} |
|||
The JavaScript language provides six [[primitive data type]]s: |
|||
* <code>Undefined</code> |
|||
* <code>Number</code> |
|||
* <code>BigInt</code> |
|||
* <code>String</code> |
|||
* <code>Boolean</code> |
|||
* <code>Symbol</code> |
|||
Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries. These named values are described within the appropriate sections below. |
|||
===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. |
|||
Note: undefined is considered a genuine primitive type. Unless explicitly converted, the undefined value may behave unexpectedly in comparison to other types that evaluate to false in a logical context. |
|||
<syntaxhighlight lang="javascript"> |
|||
let test; // variable declared, but not defined, ... |
|||
// ... set to value of undefined |
|||
const testObj = {}; |
|||
console.log(test); // test variable exists, but value not ... |
|||
// ... defined, displays undefined |
|||
console.log(testObj.myProp); // testObj exists, property does not, ... |
|||
// ... displays undefined |
|||
console.log(undefined == null); // unenforced type during check, displays true |
|||
console.log(undefined === null); // enforce type during check, displays false |
|||
</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 was legal 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 will not work as expected: |
|||
<syntaxhighlight lang="javascript"> |
|||
function isUndefined(x) { let 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'}} does not. |
|||
===Number=== |
|||
Numbers are represented in binary as [[IEEE 754]] [[floating point]] doubles. Although this format provides an accuracy of nearly 16 [[significant digits]], it cannot 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 false |
|||
console.log(0.94 - 0.01); // displays 0.9299999999999999 |
|||
</syntaxhighlight> |
|||
As a result, a routine such as the {{mono|toFixed()}} method should be used to round numbers whenever they are [http://www.jibbering.com/faq/#formatNumber formatted for output]. |
|||
Numbers may be specified in any of these notations: |
|||
<syntaxhighlight lang="javascript"> |
|||
345; // an "integer", although there is only one numeric type in JavaScript |
|||
34.5; // a floating-point number |
|||
3.45e2; // another floating-point, equivalent to 345 |
|||
0b1011; // a binary integer equal to 11 |
|||
0o377; // an octal integer equal to 255 |
|||
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 doesn't 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> |
|||
The extents [[extended real number line|'''+∞''', '''−∞''']] and '''[[NaN]]''' (Not a Number) of the number type may be obtained by two to three (including −∞) program expressions: |
|||
<syntaxhighlight lang="javascript"> |
|||
Infinity; // positive infinity |
|||
-Infinity; // negative infinity (not its own expression, just Infinity but negative) |
|||
NaN; // The Not-A-Number value, also returned as a failure in ... |
|||
// ... string-to-number conversions |
|||
</syntaxhighlight> |
|||
Infinity and NaN are numbers: |
|||
<syntaxhighlight lang="javascript"> |
|||
typeof Infinity; // returns "number" |
|||
typeof NaN; // returns "number" |
|||
</syntaxhighlight> |
|||
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"> |
|||
const myString = "123.456"; |
|||
const myNumber1 = Number(myString); |
|||
const myNumber2 = +myString; |
|||
</syntaxhighlight> |
|||
When used as a constructor, a numeric ''wrapper'' object is created (though it is of little use): |
|||
<syntaxhighlight lang="javascript"> |
|||
const myNumericWrapper = new Number(123.456); |
|||
</syntaxhighlight> |
|||
However, NaN is not equal to itself: |
|||
<syntaxhighlight lang="javascript"> |
|||
const nan = NaN; |
|||
console.log(NaN == NaN); // false |
|||
console.log(NaN === NaN); // false |
|||
console.log(NaN !== NaN); // true |
|||
console.log(nan !== nan); // true |
|||
// The isNaN methods can be used to check for NaN |
|||
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); // Also does that using the BigInt function instead |
|||
</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, as well as embedded expressions using the syntax <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 |access-date=4 November 2023 |archive-date=31 March 2022 |archive-url=https://web.archive.org/web/20220331204510/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals |url-status=live }}</ref> |
|||
<syntaxhighlight lang="javascript"> |
|||
const greeting = "Hello, World!"; |
|||
const anotherGreeting = 'Greetings, people of Earth.'; |
|||
const aMultilineGreeting = `Warm regards, |
|||
John Doe.` |
|||
// Template literals type-coerce evaluated expressions and interpolate them into the string. |
|||
const templateLiteral = `This is what is stored in anotherGreeting: ${anotherGreeting}.`; |
|||
console.log(templateLiteral); // 'This is what is stored in anotherGreeting: 'Greetings, people of Earth.'' |
|||
console.log(`You are ${Math.floor(age)=>18 ? "allowed" : "not allowed"} to view this web page`); |
|||
</syntaxhighlight> |
|||
Individual characters within a string can be accessed using the {{mono|charAt}} method (provided by {{mono|String.prototype}}). This is the preferred way when accessing individual characters within a string, because it also works in non-modern browsers: |
|||
<syntaxhighlight lang="javascript"> |
|||
const h = greeting.charAt(0); |
|||
</syntaxhighlight> |
|||
In modern browsers, individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays: |
|||
<syntaxhighlight lang="javascript"> |
|||
const h = greeting[0]; |
|||
</syntaxhighlight> |
|||
However, JavaScript strings are [[immutable object|immutable]]: |
|||
<syntaxhighlight lang="javascript"> |
|||
greeting[0] = "H"; // Fails |
|||
</syntaxhighlight> |
|||
Applying the equality operator ("==") to two strings returns true, if the strings have the same contents, which means: of the same length and containing the same sequence of characters (case is significant for alphabets). Thus: |
|||
<syntaxhighlight lang="javascript"> |
|||
const x = "World"; |
|||
const compare1 = ("Hello, " + x == "Hello, World"); // Here compare1 contains true. |
|||
const compare2 = ("Hello, " + x == "hello, World"); // Here compare2 contains ... |
|||
// ... false since the ... |
|||
// ... first characters ... |
|||
// ... of both operands ... |
|||
// ... are not of the same case. |
|||
</syntaxhighlight> |
|||
Quotes of the same type cannot be nested unless they are [[String literal#Escape character|escaped]]. |
|||
<syntaxhighlight lang="javascript"> |
|||
let x = '"Hello, World!" he said.'; // Just fine |
|||
x = ""Hello, World!" he said."; // Not good |
|||
x = "\"Hello, World!\" he said."; // Works by escaping " with \" |
|||
</syntaxhighlight> |
|||
The {{mono|String}} constructor creates a string object (an object wrapping a string): |
|||
<syntaxhighlight lang="javascript"> |
|||
const 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"> |
|||
const s = new String("Hello !"); |
|||
typeof s; // Is 'object' |
|||
typeof s.valueOf(); // Is 'string' |
|||
</syntaxhighlight> |
|||
Equality between two {{mono|String}} objects does not behave as with string primitives: |
|||
<syntaxhighlight lang="javascript"> |
|||
const s1 = new String("Hello !"); |
|||
const s2 = new String("Hello !"); |
|||
s1 == s2; // Is false, because they are two distinct objects |
|||
s1.valueOf() == s2.valueOf(); // Is true |
|||
</syntaxhighlight> |
|||
===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 conversion]]. 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. |
|||
=== Type conversion === |
|||
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 ==== |
|||
{{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>). |
|||
<syntaxhighlight lang="javascript"> |
|||
// Automatic type coercion |
|||
console.log(true == 2 ); // false... true → 1 !== 2 ← 2 |
|||
console.log(false == 2 ); // false... false → 0 !== 2 ← 2 |
|||
console.log(true == 1 ); // true.... true → 1 === 1 ← 1 |
|||
console.log(false == 0 ); // true.... false → 0 === 0 ← 0 |
|||
console.log(true == "2"); // false... true → 1 !== 2 ← "2" |
|||
console.log(false == "2"); // false... false → 0 !== 2 ← "2" |
|||
console.log(true == "1"); // true.... true → 1 === 1 ← "1" |
|||
console.log(false == "0"); // true.... false → 0 === 0 ← "0" |
|||
console.log(false == "" ); // true.... false → 0 === 0 ← "" |
|||
console.log(false == NaN); // false... false → 0 !== NaN |
|||
console.log(NaN == NaN); // false...... NaN is not equivalent to anything, including NaN. |
|||
// Type checked comparison (no conversion of types and values) |
|||
console.log(true === 1); // false...... data types do not match |
|||
// Explicit type coercion |
|||
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" numbers |
|||
console.log("0" ? true : false); // true.... only the empty string is "falsy" |
|||
console.log(Boolean({})); // true.... all objects are "truthy" |
|||
</syntaxhighlight> |
|||
The new operator can be used to create an object wrapper for a Boolean primitive. However, the {{mono|typeof}} operator does not return {{mono|boolean}} for the object wrapper, it returns {{mono|object}}. Because all objects evaluate as {{mono|true}}, a method such as {{mono|.valueOf()}}, or {{mono|.toString()}}, must be used to retrieve the wrapped value. For explicit coercion to the Boolean type, Mozilla recommends that the {{mono|Boolean()}} function (without {{mono|new}}) be used in preference to the Boolean object. |
|||
<syntaxhighlight lang="javascript"> |
|||
const b = new Boolean(false); // Object false {} |
|||
const t = Boolean(b); // Boolean true |
|||
const f = Boolean(b.valueOf()); // Boolean false |
|||
let n = new Boolean(b); // Not recommended |
|||
n = new Boolean(b.valueOf()); // Preferred |
|||
if (0 || -0 || "" || null || undefined || b.valueOf() || !new Boolean() || !t) { |
|||
console.log("Never this"); |
|||
} else if ([] && {} && b && typeof b === "object" && b.toString() === "false") { |
|||
console.log("Always this"); |
|||
} |
|||
</syntaxhighlight> |
|||
===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> |
|||
Example: |
|||
<syntaxhighlight lang="javascript"> |
|||
let x = Symbol(1); |
|||
const y = Symbol(1); |
|||
x === y; // => false |
|||
const symbolObject = {}; |
|||
const normalObject = {}; |
|||
// since x and y are unique, |
|||
// they can be used as unique keys in an object |
|||
symbolObject[x] = 1; |
|||
symbolObject[y] = 2; |
|||
symbolObject[x]; // => 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 --> |
|||
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 |
|||
x[Symbol.iterator] === Array.prototype[Symbol.iterator]; // and Arrays are iterable |
|||
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> |
|||
==Native objects== |
|||
The JavaScript language provides a handful of native [[Object (computer science)|objects]]. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available. |
|||
===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>). |
|||
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 <code>push</code> method occupies the 0th index of the array. |
|||
<syntaxhighlight lang="javascript"> |
|||
const 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 <code>length</code> 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 <code>length</code> property will remove larger indices. |
|||
Elements of <code>Array</code>s may be accessed using normal object property access notation: |
|||
<syntaxhighlight lang="javascript"> |
|||
myArray[1]; // the 2nd item in myArray |
|||
myArray["1"]; |
|||
</syntaxhighlight> |
|||
The above two are equivalent. It is not possible to use the "dot"-notation or strings with alternative representations of the number: |
|||
<syntaxhighlight lang="javascript"> |
|||
myArray.1; // syntax error |
|||
myArray["01"]; // not the same as myArray[1] |
|||
</syntaxhighlight> |
|||
Declaration of an array can use either an <code>Array</code> literal or the <code>Array</code> constructor: |
|||
<syntaxhighlight lang="javascript"> |
|||
let myArray; |
|||
// Array literals |
|||
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 <code>length</code> 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" |
|||
</syntaxhighlight> |
|||
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both. (Technically, JavaScript does not support multidimensional arrays, but one can mimic them with arrays-of-arrays.) |
|||
<syntaxhighlight lang="javascript"> |
|||
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" |
|||
dogs.rover.color; // results in "brown" |
|||
</syntaxhighlight> |
|||
===Date=== |
|||
A <code>Date</code> 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 <code>Date</code> constructor. Note that months are zero-based. |
|||
<syntaxhighlight lang="javascript"> |
|||
new Date(); // create a new Date instance representing the current time/date. |
|||
new Date(2010, 2, 1); // create a new Date instance representing 2010-Mar-01 00:00:00 |
|||
new Date(2010, 2, 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> |
|||
Methods to extract fields are provided, as well as a useful <code>toString</code>: |
|||
<syntaxhighlight lang="javascript"> |
|||
const d = new Date(2010, 2, 1, 14, 25, 30); // 2010-Mar-01 14:25:30; |
|||
// Displays '2010-3-1 14:25:30': |
|||
console.log(d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' |
|||
+ d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()); |
|||
// Built-in toString returns something like 'Mon 1 March, 2010 14:25:30 GMT-0500 (EST)': |
|||
console.log(d); |
|||
</syntaxhighlight> |
|||
===Error=== |
|||
Custom error messages can be created using the <code>Error</code> class: |
|||
<syntaxhighlight lang="javascript"> |
|||
throw new Error("Something went wrong."); |
|||
</syntaxhighlight> |
|||
These can be caught by try...catch...finally blocks as described in the section on [[#Exception_handling|exception handling]]. |
|||
===Math=== |
|||
The {{mono|Math}} object contains various math-related constants (for example, {{pi}}) and functions (for example, cosine). (Note that the {{mono|Math}} object has no constructor, unlike {{mono|Array}} or {{mono|Date}}. 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" |
|||
|+ Some of the constants contained in the Math object |
|||
|- |
|||
!Property!!Returned value<br />rounded to 5 digits!!Description |
|||
|- |
|||
| {{mono|Math.E}} || 2.7183 || {{mvar|[[e (mathematical constant)|e]]}}: Natural logarithm base |
|||
|- |
|||
| {{mono|Math.LN2}} || 0.69315 || [[Natural logarithm]] of 2 |
|||
|- |
|||
| {{mono|Math.LN10}} || 2.3026 || Natural logarithm of 10 |
|||
|- |
|||
| {{mono|Math.LOG2E}} || 1.4427 || [[Logarithm]] to the base 2 of {{mvar|e}} |
|||
|- |
|||
| {{mono|Math.LOG10E}} || 0.43429 || Logarithm to the base 10 of {{mvar|e}} |
|||
|- |
|||
| {{mono|Math.PI}} || 3.14159 || [[Pi|{{pi}}]]: circumference/diameter of a circle |
|||
|- |
|||
| {{mono|Math.SQRT1_2}} || 0.70711 || [[Square root]] of ½ |
|||
|- |
|||
| {{mono|Math.SQRT2}} || 1.4142 || [[Square root of 2]] |
|||
|} |
|||
{| class="wikitable" border="1" |
|||
|+ Methods of the Math object |
|||
|- |
|||
!Example!!Returned value<br />rounded to 5 digits!!Description |
|||
|- |
|||
| {{mono|Math.abs(-2.3)}} || 2.3 || [[Absolute value]] |
|||
|- |
|||
| {{mono|Math.acos(Math.SQRT1_2)}} || {{val|0.78540|ul=rad|fmt=none}} = 45° || [[Arccosine]] |
|||
|- |
|||
| {{mono|Math.asin(Math.SQRT1_2)}} || {{val|0.78540|u=rad|fmt=none}} = 45° || [[Arcsine]] |
|||
|- |
|||
| {{mono|Math.atan(1)}} || {{val|0.78540|u=rad|fmt=none}} = 45° || Half circle [[arctangent]] ({{tmath|-\pi/2}} to {{tmath|+\pi/2}}) |
|||
|- |
|||
| {{mono|Math.atan2(-3.7, -3.7)}} || {{val|-2.3562|u=rad}} = {{val|-135|u=deg}} || Whole circle arctangent ({{tmath|-\pi}} to {{tmath|+\pi}}) |
|||
|- |
|||
| {{mono|Math.ceil(1.1)}} || 2 || Ceiling: [[rounding|round]] up to smallest integer ≥ argument |
|||
|- |
|||
| {{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 |
|||
|- |
|||
| {{mono|Math.log(Math.E)}} || 1 || Natural logarithm, base {{mvar|e}} |
|||
|- |
|||
| {{mono|Math.max(1, -2)}} || 1 || Maximum: {{mono|(x > y) ? x : y}} |
|||
|- |
|||
| {{mono|Math.min(1, -2)}} || {{val|-2}} || Minimum: {{mono|(x < y) ? x : y}} |
|||
|- |
|||
| {{mono|Math.pow(-3, 2)}} || 9 || [[Exponentiation]] (raised to the power of): {{mono|Math.pow(x, y)}} gives x<sup>y</sup> |
|||
|- |
|||
| {{mono|Math.random()}} || e.g. 0.17068 || [[Pseudorandom]] number between 0 (inclusive) and 1 (exclusive) |
|||
|- |
|||
| {{mono|Math.round(1.5)}} || 2 || Round to the nearest integer; half fractions are rounded up (e.g. 1.5 rounds to 2) |
|||
|- |
|||
| {{mono|Math.sin(Math.PI/4)}} || 0.70711 || [[Sine]] |
|||
|- |
|||
| {{mono|Math.sqrt(49)}} || 7 || Square root |
|||
|- |
|||
| {{mono|Math.tan(Math.PI/4)}} || 1 || [[Trigonometric functions|Tangent]] |
|||
|} |
|||
===Regular expression=== |
|||
{{main|Regular expression}} |
|||
<syntaxhighlight lang="javascript"> |
|||
/expression/.test(string); // returns Boolean |
|||
"string".search(/expression/); // returns position Number |
|||
"string".replace(/expression/, replacement); |
|||
// Here are some examples |
|||
if (/Tom/.test("My name is Tom")) console.log("Hello Tom!"); |
|||
console.log("My name is Tom".search(/Tom/)); // == 11 (characters before Tom) |
|||
console.log("My name is Tom".replace(/Tom/, "John")); // == "My name is John" |
|||
</syntaxhighlight> |
|||
====Character classes==== |
|||
<syntaxhighlight lang="javascript"> |
|||
// \d - digit |
|||
// \D - non digit |
|||
// \s - space |
|||
// \S - non space |
|||
// \w - word char |
|||
// \W - non word |
|||
// [ ] - one of |
|||
// [^] - one not of |
|||
// - - range |
|||
if (/\d/.test('0')) console.log('Digit'); |
|||
if (/[0-9]/.test('6')) console.log('Digit'); |
|||
if (/[13579]/.test('1')) console.log('Odd number'); |
|||
if (/\S\S\s\S\S\S\S/.test('My name')) console.log('Format OK'); |
|||
if (/\w\w\w/.test('Tom')) console.log('Hello Tom'); |
|||
if (/[a-zA-Z]/.test('B')) console.log('Letter'); |
|||
</syntaxhighlight> |
|||
====Character matching==== |
|||
<syntaxhighlight lang="javascript"> |
|||
// A...Z a...z 0...9 - alphanumeric |
|||
// \u0000...\uFFFF - Unicode hexadecimal |
|||
// \x00...\xFF - ASCII hexadecimal |
|||
// \t - tab |
|||
// \n - new line |
|||
// \r - CR |
|||
// . - any character |
|||
// | - OR |
|||
if (/T.m/.test('Tom')) console.log ('Hi Tom, Tam or Tim'); |
|||
if (/A|B/.test("A")) console.log ('A or B'); |
|||
</syntaxhighlight> |
|||
====Repeaters==== |
|||
<syntaxhighlight lang="javascript"> |
|||
// ? - 0 or 1 match |
|||
// * - 0 or more |
|||
// + - 1 or more |
|||
// {n} - exactly n |
|||
// {n,} - n or more |
|||
// {0,n} - n or less |
|||
// {n,m} - range n to m |
|||
if (/ab?c/.test("ac")) console.log("OK"); // match: "ac", "abc" |
|||
if (/ab*c/.test("ac")) console.log("OK"); // match: "ac", "abc", "abbc", "abbbc" etc. |
|||
if (/ab+c/.test("abc")) console.log("OK"); // match: "abc", "abbc", "abbbc" etc. |
|||
if (/ab{3}c/.test("abbbc")) console.log("OK"); // match: "abbbc" |
|||
if (/ab{3,}c/.test("abbbc")) console.log("OK"); // match: "abbbc", "abbbbc", "abbbbbc" etc. |
|||
if (/ab{1,3}c/.test("abc")) console.log("OK"); // match: "abc", "abbc", "abbbc" |
|||
</syntaxhighlight> |
|||
====Anchors==== |
|||
<syntaxhighlight lang="javascript"> |
|||
// ^ - string starts with |
|||
// $ - string ends with |
|||
if (/^My/.test("My name is Tom")) console.log ("Hi!"); |
|||
if (/Tom$/.test("My name is Tom")) console.log ("Hi Tom!"); |
|||
</syntaxhighlight> |
|||
====Subexpression==== |
|||
<syntaxhighlight lang="javascript"> |
|||
// ( ) - groups characters |
|||
if (/water(mark)?/.test("watermark")) console.log("Here is water!"); // match: "water", "watermark", |
|||
if (/(Tom)|(John)/.test("John")) console.log("Hi Tom or John!"); |
|||
</syntaxhighlight> |
|||
====Flags==== |
|||
<syntaxhighlight lang="javascript"> |
|||
// /g - global |
|||
// /i - ignore upper/lower case |
|||
// /m - allow matches to span multiple lines |
|||
console.log("hi tom!".replace(/Tom/i, "John")); // == "hi John!" |
|||
console.log("ratatam".replace(/ta/, "tu")); // == "ratutam" |
|||
console.log("ratatam".replace(/ta/g, "tu")); // == "ratutum" |
|||
</syntaxhighlight> |
|||
====Advanced methods==== |
|||
<syntaxhighlight lang="javascript"> |
|||
my_array = my_string.split(my_delimiter); |
|||
// example |
|||
my_array = "dog,cat,cow".split(","); // my_array==["dog","cat","cow"]; |
|||
my_array = my_string.match(my_expression); |
|||
// example |
|||
my_array = "We start at 11:30, 12:15 and 16:45".match(/\d\d:\d\d/g); // my_array==["11:30","12:15","16:45"]; |
|||
</syntaxhighlight> |
|||
====Capturing groups==== |
|||
<syntaxhighlight lang="javascript"> |
|||
const myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/; |
|||
const results = myRe.exec("The date and time are 2009-09-08 09:37:08."); |
|||
if (results) { |
|||
console.log("Matched: " + results[0]); // Entire match |
|||
const my_date = results[1]; // First group == "2009-09-08" |
|||
const 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 <code>Function</code> 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. |
|||
const add = new Function('x', 'y', 'return x + y'); |
|||
add(1, 2); // => 3 |
|||
</syntaxhighlight> |
|||
The add function above may also be defined using a function expression: |
|||
<syntaxhighlight lang="javascript"> |
|||
const add = function(x, y) { |
|||
return x + y; |
|||
}; |
|||
add(1, 2); // => 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. |
|||
<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"> |
|||
function add(x, y) { |
|||
return x + y; |
|||
} |
|||
add(1, 2); // => 3 |
|||
</syntaxhighlight> |
|||
Hoisting allows users to use the function before it is "declared": |
|||
<syntaxhighlight lang="javascript"> |
|||
add(1, 2); // => 3, not a ReferenceError |
|||
function add(x, y) { |
|||
return x + y; |
|||
} |
|||
</syntaxhighlight> |
|||
A function instance has properties and methods. |
|||
<syntaxhighlight lang="javascript"> |
|||
function subtract(x, y) { |
|||
return x - y; |
|||
} |
|||
console.log(subtract.length); // => 2, arity of the function (number of arguments) |
|||
console.log(subtract.toString()); |
|||
/* |
|||
"function subtract(x, y) { |
|||
return x - y; |
|||
}" |
|||
*/ |
|||
</syntaxhighlight> |
|||
==Operators== |
|||
The '+' operator is [[Operator overloading|overloaded]]: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number. |
|||
<syntaxhighlight lang="javascript"> |
|||
// Concatenate 2 strings |
|||
console.log('He' + 'llo'); // displays Hello |
|||
// Add two numbers |
|||
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 |
|||
console.log('$' + (3 + 4)); // displays $7 |
|||
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 |
|||
</syntaxhighlight> |
|||
Similarly, the '*' operator is overloaded: it can convert a string into a number. |
|||
<syntaxhighlight lang="javascript"> |
|||
console.log(2 + '6'*1); // displays 8 |
|||
console.log(3*'7'); // 21 |
|||
console.log('3'*'7'); // 21 |
|||
console.log('hello'*'world'); // displays NaN |
|||
</syntaxhighlight> |
|||
===Arithmetic=== |
|||
JavaScript supports the following '''binary arithmetic operators''': |
|||
{| class="wikitable" |
|||
|- |
|||
| align="center" | <code>+</code> || addition |
|||
|- |
|||
| align="center" | <code>-</code> || subtraction |
|||
|- |
|||
| align="center" | <code>*</code> || multiplication |
|||
|- |
|||
| align="center" | <code>/</code> || division (returns a floating-point value) |
|||
|- |
|||
| align="center" | <code>%</code> || modulo (returns the remainder) |
|||
|- |
|||
| align="center" | <code>**</code> || exponentiation |
|||
|} |
|||
JavaScript supports the following '''unary arithmetic operators''': |
|||
{| class="wikitable" |
|||
|- |
|||
| align="center" | <code>+</code> || unary conversion of string to number |
|||
|- |
|||
| align="center" | <code>-</code> || unary negation (reverses the sign) |
|||
|- |
|||
| align="center" | <code>++</code> || increment (can be prefix or postfix) |
|||
|- |
|||
| align="center" | <code>--</code> || decrement (can be prefix or postfix) |
|||
|} |
|||
<syntaxhighlight lang="javascript"> |
|||
let x = 1; |
|||
console.log(++x); // x becomes 2; displays 2 |
|||
console.log(x++); // displays 2; x becomes 3 |
|||
console.log(x); // x is 3; displays 3 |
|||
console.log(x--); // displays 3; x becomes 2 |
|||
console.log(x); // displays 2; x is 2 |
|||
console.log(--x); // x becomes 1; displays 1 |
|||
</syntaxhighlight> |
|||
The modulo operator displays the remainder after division by the modulus. If negative numbers are involved, the returned value depends on the operand. |
|||
<syntaxhighlight lang="javascript"> |
|||
const x = 17; |
|||
console.log(x%5); // displays 2 |
|||
console.log(x%6); // displays 5 |
|||
console.log(-x%5); // displays -2 |
|||
console.log(-x%-5); // displays -2 |
|||
console.log(x%-5); // displays 2 |
|||
</syntaxhighlight> |
|||
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again: |
|||
<syntaxhighlight lang="javascript"> |
|||
const 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> |
|||
===Assignment=== |
|||
{| class="wikitable" |
|||
|- |
|||
| align="center" | <code>=</code> || assign |
|||
|- |
|||
| align="center" | <code>+=</code> || add and assign |
|||
|- |
|||
| align="center" | <code>-=</code> || subtract and assign |
|||
|- |
|||
| align="center" | <code>*=</code> || multiply and assign |
|||
|- |
|||
| align="center" | <code>/=</code> || divide and assign |
|||
|- |
|||
| align="center" | <code>%=</code> || modulo and assign |
|||
|- |
|||
| align="center" | <code>**=</code> || exponentiation and assign |
|||
|} |
|||
[[Assignment (computer science)|Assignment]] of [[primitive type]]s |
|||
<syntaxhighlight lang="javascript"> |
|||
let x = 9; |
|||
x += 1; |
|||
console.log(x); // displays: 10 |
|||
x *= 30; |
|||
console.log(x); // displays: 300 |
|||
x /= 6; |
|||
console.log(x); // displays: 50 |
|||
x -= 3; |
|||
console.log(x); // displays: 47 |
|||
x %= 7; |
|||
console.log(x); // displays: 5 |
|||
</syntaxhighlight> |
|||
Assignment of object types |
|||
<syntaxhighlight lang="javascript"> |
|||
/** |
|||
* To learn JavaScript objects... |
|||
*/ |
|||
const object_1 = {a: 1}; // assign reference of newly created object to object_1 |
|||
let object_2 = {a: 0}; |
|||
let object_3 = object_2; // object_3 references the same object as object_2 does |
|||
object_3.a = 2; |
|||
message(); // displays 1 2 2 |
|||
object_2 = object_1; // object_2 now references the same object as object_1 |
|||
// object_3 still references what object_2 referenced before |
|||
message(); // displays 1 1 2 |
|||
object_2.a = 7; // modifies object_1 |
|||
message(); // displays 7 7 2 |
|||
object_3.a = 5; // object_3 does not change object_2 |
|||
message(); // displays 7 7 5 |
|||
object_3 = object_2; |
|||
object_3.a=4; // object_3 changes object_1 and object_2 |
|||
message(); // displays 4 4 4 |
|||
/** |
|||
* Prints the console.log message |
|||
*/ |
|||
function message() { |
|||
console.log(object_1.a + " " + object_2.a + " " + object_3.a); |
|||
} |
|||
</syntaxhighlight> |
|||
==== Destructuring assignment ==== |
|||
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leaves that are to receive the substructures of the assigned value. |
|||
<syntaxhighlight lang="javascript"> |
|||
let 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']}; |
|||
const arr = []; |
|||
({baz: [arr[0], arr[3]], foo: a, bar: b} = e); |
|||
console.log(`${a},${b},${arr}`); // displays: 5,6,Baz,,,Content |
|||
[a, b] = [b, a]; // swap contents of a and b |
|||
console.log(a + ',' + b); // displays: 6,5 |
|||
[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 introduced the "<code>...</code>" array operator, for the related concepts of "spread syntax"<ref>{{Cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax|title=Spread syntax (...) - JavaScript | 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. For arrays, it indicates that the elements 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"> |
|||
const a = [1, 2, 3, 4]; |
|||
// It can be used multiple times in the same expression |
|||
const b = [...a, ...a]; // b = [1, 2, 3, 4, 1, 2, 3, 4]; |
|||
// It can be combined with non-spread items. |
|||
const 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. |
|||
const 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}`); |
|||
} |
|||
// Users 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]); |
|||
// Users 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); |
|||
// For comparison, doing this without the spread operator |
|||
// 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 <code>...</code> 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 <code>Array</code> 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"> |
|||
function foo(a, b, ...c) { |
|||
console.log(c.length); |
|||
} |
|||
foo(1, 2, 3, 4, 5); // "3" → c = [3, 4, 5] |
|||
foo('a', 'b'); // "0" → c = [] |
|||
</syntaxhighlight> |
|||
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. |
|||
===Comparison=== |
|||
{| class=wikitable |
|||
|- |
|||
| align="center" | <code>==</code> || equal |
|||
|- |
|||
| align="center" | <code>!=</code> || not equal |
|||
|- |
|||
| align="center" | <code>></code> || greater than |
|||
|- |
|||
| align="center" | <code>>=</code> || greater than or equal to |
|||
|- |
|||
| align="center" | <code><</code> || less than |
|||
|- |
|||
| align="center" | <code><=</code> || less than or equal to |
|||
|- |
|||
| align="center" | <code>===</code> || identical (equal and of same type) |
|||
|- |
|||
| align="center" | <code>!==</code> || not identical |
|||
|} |
|||
Variables referencing objects are equal or identical only if they reference the same object: |
|||
<syntaxhighlight lang="javascript"> |
|||
const obj1 = {a: 1}; |
|||
const obj2 = {a: 1}; |
|||
const obj3 = obj1; |
|||
console.log(obj1 == obj2); //false |
|||
console.log(obj3 == obj1); //true |
|||
console.log(obj3 === obj1); //true |
|||
</syntaxhighlight> |
|||
See also [[#String|String]]. |
|||
===Logical=== |
|||
JavaScript provides four logical operators: |
|||
* unary [[negation]] (<code>NOT = !a</code>) |
|||
* binary [[logical disjunction|disjunction]] (<code>OR = a || b</code>) and [[logical conjunction|conjunction]] (<code>AND = a && b</code>) |
|||
* ternary [[Conditional (programming)|conditional]] (<code>c ? t : f</code>) |
|||
In the context of a logical operation, any expression evaluates to true except the following''':''' |
|||
* Strings: <code>""</code>, <code><nowiki>''</nowiki></code>, |
|||
* Numbers: <code>0</code>, <code>-0</code>, <code>NaN</code>, |
|||
* Special: <code>null</code>, <code>undefined</code>, |
|||
* Boolean: <code>false</code>. |
|||
The Boolean function can be used to explicitly convert to a primitive of type <code>Boolean</code>: |
|||
<syntaxhighlight lang="javascript"> |
|||
// Only empty strings return false |
|||
console.log(Boolean("") === false); |
|||
console.log(Boolean("false") === true); |
|||
console.log(Boolean("0") === true); |
|||
// Only zero and NaN return false |
|||
console.log(Boolean(NaN) === false); |
|||
console.log(Boolean(0) === false); |
|||
console.log(Boolean(-0) === false); // equivalent to -1*0 |
|||
console.log(Boolean(-2) === true); |
|||
// All objects return true |
|||
console.log(Boolean(this) === true); |
|||
console.log(Boolean({}) === true); |
|||
console.log(Boolean([]) === true); |
|||
// These types return false |
|||
console.log(Boolean(null) === false); |
|||
console.log(Boolean(undefined) === false); // equivalent to Boolean() |
|||
</syntaxhighlight> |
|||
The NOT operator evaluates its operand as a Boolean and returns the negation. Using the operator twice in a row, as a [[double negative]], explicitly converts an expression to a primitive of type Boolean: |
|||
<syntaxhighlight lang="javascript"> |
|||
console.log( !0 === Boolean(!0)); |
|||
console.log(Boolean(!0) === !!1); |
|||
console.log(!!1 === Boolean(1)); |
|||
console.log(!!0 === Boolean(0)); |
|||
console.log(Boolean(0) === !1); |
|||
console.log(!1 === Boolean(!1)); |
|||
console.log(!"" === Boolean(!"")); |
|||
console.log(Boolean(!"") === !!"s"); |
|||
console.log(!!"s" === Boolean("s")); |
|||
console.log(!!"" === Boolean("")); |
|||
console.log(Boolean("") === !"s"); |
|||
console.log(!"s" === Boolean(!"s")); |
|||
</syntaxhighlight> |
|||
The ternary operator can also be used for explicit conversion: |
|||
<syntaxhighlight lang="javascript"> |
|||
console.log([] == false); console.log([] ? true : false); // “truthy”, but the comparison uses [].toString() |
|||
console.log([0] == false); console.log([0]? true : false); // [0].toString() == "0" |
|||
console.log("0" == false); console.log("0"? true : false); // "0" → 0 ... (0 == 0) ... 0 ← false |
|||
console.log([1] == true); console.log([1]? true : false); // [1].toString() == "1" |
|||
console.log("1" == true); console.log("1"? true : false); // "1" → 1 ... (1 == 1) ... 1 ← true |
|||
console.log([2] != true); console.log([2]? true : false); // [2].toString() == "2" |
|||
console.log("2" != true); console.log("2"? true : false); // "2" → 2 ... (2 != 1) ... 1 ← true |
|||
</syntaxhighlight> |
|||
Expressions that use features such as post–incrementation (<code>i++</code>) 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"> |
|||
console.log(a || b); // When a is true, there is no reason to evaluate b. |
|||
console.log(a && b); // When a is false, there is no reason to evaluate b. |
|||
console.log(c ? t : f); // When c is true, there is no reason to evaluate f. |
|||
</syntaxhighlight> |
|||
In early versions of JavaScript and [[JScript]], the binary logical operators returned a Boolean value (like most C-derived programming languages). However, all contemporary implementations return one of their operands instead: |
|||
<syntaxhighlight lang="javascript"> |
|||
console.log(a || b); // if a is true, return a, otherwise return b |
|||
console.log(a && b); // if a is false, return a, otherwise return b |
|||
</syntaxhighlight> |
|||
Programmers who are more familiar with the behavior in C might find this feature surprising, but it allows for a more concise expression of patterns like [[null coalescing operator|null coalescing]]: |
|||
<syntaxhighlight lang="javascript"> |
|||
const s = t || "(default)"; // assigns t, or the default value, if t is null, empty, etc. |
|||
</syntaxhighlight> |
|||
=== Logical assignment === |
|||
{| class="wikitable" |
|||
|- |
|||
| 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" | <code>&</code> || AND |
|||
|- |
|||
| align="center" | <code>|</code> || OR |
|||
|- |
|||
| align="center" | <code>^</code> || XOR |
|||
|- |
|||
| align="center" | <code>!</code> || NOT |
|||
|- |
|||
| align="center" | <code><<</code> || shift left (zero fill at right) |
|||
|- |
|||
| align="center" | <code>>></code> || shift right (sign-propagating); copies of the<br />leftmost bit (sign bit) are shifted in from the left |
|||
|- |
|||
| align="center" | <code>>>></code> || shift right (zero fill at left). For positive numbers,<br /><code>>></code> and <code>>>></code> yield the same result. |
|||
|} |
|||
Examples: |
|||
<syntaxhighlight lang="javascript"> |
|||
const x = 11 & 6; |
|||
console.log(x); // 2 |
|||
</syntaxhighlight> |
|||
JavaScript supports the following '''unary bitwise operator''': |
|||
{| class="wikitable" |
|||
|- |
|||
| align="center" | <code>~</code> || NOT (inverts the bits) |
|||
|} |
|||
===Bitwise Assignment=== |
|||
JavaScript supports the following '''binary assignment operators:''' |
|||
{| class="wikitable" |
|||
|- |
|||
| align="center" | <code>&=</code> || and |
|||
|- |
|||
| align="center" | <code>|=</code> || or |
|||
|- |
|||
| align="center" | <code>^=</code> || xor |
|||
|- |
|||
| align="center" | <code><<=</code> || shift left (zero fill at right) |
|||
|- |
|||
| align="center" | <code>>>=</code> || shift right (sign-propagating); copies of the<br />leftmost bit (sign bit) are shifted in from the left |
|||
|- |
|||
| align="center" | <code>>>>=</code> || shift right (zero fill at left). For positive numbers,<br /><code>>>=</code> and <code>>>>=</code> yield the same result. |
|||
|} |
|||
Examples: |
|||
<syntaxhighlight lang="javascript"> |
|||
let x=7; |
|||
console.log(x); // 7 |
|||
x<<=3; |
|||
console.log(x); // 7->14->28->56 |
|||
</syntaxhighlight> |
|||
===String=== |
|||
{| class="wikitable" |
|||
|- |
|||
| align="center" | <code>=</code> || assignment |
|||
|- |
|||
| align="center" | <code>+</code> || concatenation |
|||
|- |
|||
| align="center" | <code>+=</code> || concatenate and assign |
|||
|} |
|||
Examples: |
|||
<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== |
|||
===Compound statements=== |
|||
A pair of curly brackets <code>{ }</code> and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used. |
|||
===If ... else=== |
|||
<syntaxhighlight lang="javascript"> |
|||
if (expr) { |
|||
//statements; |
|||
} else if (expr2) { |
|||
//statements; |
|||
} else { |
|||
//statements; |
|||
} |
|||
</syntaxhighlight> |
|||
=== Conditional (ternary) operator === |
|||
The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the ''if'' statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what ''if'' is to statements. |
|||
<syntaxhighlight lang="javascript"> |
|||
const result = condition ? expression : alternative; |
|||
</syntaxhighlight> |
|||
is the same as: |
|||
<syntaxhighlight lang="javascript"> |
|||
if (condition) { |
|||
const result = expression; |
|||
} else { |
|||
const result = alternative; |
|||
} |
|||
</syntaxhighlight> |
|||
Unlike the ''if'' statement, the conditional operator cannot omit its "else-branch". |
|||
===Switch statement=== |
|||
The syntax of the JavaScript [[Control flow#Choice|switch statement]] is as follows: |
|||
<syntaxhighlight lang="javascript">switch (expr) { |
|||
case SOMEVALUE: |
|||
// statements; |
|||
break; |
|||
case ANOTHERVALUE: |
|||
// statements specific to ANOTHERVALUE |
|||
// no break statement, falling through to the following case |
|||
case ORANOTHERONE: |
|||
// statements for when ANOTHERVALUE || ORANOTHERONE |
|||
break; //The buck stops here. |
|||
case YETANOTHER: |
|||
// statements; |
|||
break; |
|||
default: |
|||
// statements; |
|||
break; |
|||
}</syntaxhighlight> |
|||
* <code>break;</code> 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. |
|||
* Expressions can be used instead of values. |
|||
* The default case (optional) is executed when the expression does not match any other specified cases. |
|||
* Braces are required. |
|||
===For loop=== |
|||
The syntax of the JavaScript [[for loop]] is as follows: |
|||
<syntaxhighlight lang="javascript"> |
|||
for (initial; condition; loop statement) { |
|||
/* |
|||
statements will be executed every time |
|||
the for{} loop cycles, while the |
|||
condition is satisfied |
|||
*/ |
|||
} |
|||
</syntaxhighlight> |
|||
or |
|||
<syntaxhighlight lang="javascript"> |
|||
for (initial; condition; loop statement(iteration)) // one statement |
|||
</syntaxhighlight> |
|||
===For ... in loop=== |
|||
The syntax of the JavaScript <code>[[Foreach loop|for ... in loop]]</code> is as follows: |
|||
<syntaxhighlight lang="javascript"> |
|||
for (var property_name in some_object) { |
|||
// statements using some_object[property_name]; |
|||
} |
|||
</syntaxhighlight> |
|||
* 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=== |
|||
The syntax of the JavaScript [[while loop]] is as follows: |
|||
<syntaxhighlight lang="javascript"> |
|||
while (condition) { |
|||
statement1; |
|||
statement2; |
|||
statement3; |
|||
... |
|||
} |
|||
</syntaxhighlight> |
|||
===Do ... while loop=== |
|||
The syntax of the JavaScript <code>[[do while loop|do ... while loop]]</code> is as follows: |
|||
<syntaxhighlight lang="javascript"> |
|||
do { |
|||
statement1; |
|||
statement2; |
|||
statement3; |
|||
... |
|||
} while (condition); |
|||
</syntaxhighlight> |
|||
===With=== |
|||
The with statement adds all of the given object's properties and methods into the following block's scope, letting them be referenced as if they were local variables. |
|||
<syntaxhighlight lang="javascript"> |
|||
with (document) { |
|||
const a = getElementById('a'); |
|||
const b = getElementById('b'); |
|||
const c = getElementById('c'); |
|||
}; |
|||
</syntaxhighlight> |
|||
* Note the absence of {{mono|document.}} before each {{mono|getElementById()}} invocation. |
|||
The semantics are similar to the with statement of [[Pascal (programming language)|Pascal]]. |
|||
Because the availability of with statements hinders program performance and is believed to reduce code clarity (since any given variable could actually be a property from an enclosing {{mono|with}}), this statement is not allowed in ''strict mode''. |
|||
===Labels=== |
|||
JavaScript supports nested labels in most implementations. Loops or blocks can be labeled 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 (let a = 0; a < 10; ++a) { |
|||
if (a === 4) break loop1; // Stops after the 4th attempt |
|||
console.log('a = ' + a); |
|||
loop2: for (let 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 |
|||
console.log('b = ' + b); |
|||
} //end of loop2 |
|||
console.log('finished'); |
|||
} //end of loop1 |
|||
block1: { |
|||
console.log('Hello'); // Displays 'Hello' |
|||
break block1; |
|||
console.log('World'); // Will never get here |
|||
} |
|||
goto block1; // Parse error. |
|||
</syntaxhighlight> |
|||
==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 a user 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); |
|||
let difference = number1 - number2; |
|||
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, |
|||
//'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> |
|||
Functions are [[first-class citizen]]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 <code>.length</code> property, it is ''not'' an instance of {{mono|Array}}; it does not have methods such as {{mono|.slice()}}, {{mono|.sort()}}, etc.) |
|||
<syntaxhighlight lang="javascript"> |
|||
function add7(x, y) { |
|||
if (!y) { |
|||
y = 7; |
|||
} |
|||
console.log(x + y + arguments.length); |
|||
}; |
|||
add7(3); // 11 |
|||
add7(3, 4); // 9 |
|||
</syntaxhighlight> |
|||
Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed. |
|||
<syntaxhighlight lang="javascript"> |
|||
const obj1 = {a : 1}; |
|||
const obj2 = {b : 2}; |
|||
function foo(p) { |
|||
p = obj2; // Ignores actual parameter |
|||
p.b = arguments[1]; |
|||
} |
|||
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter |
|||
console.log(`${obj1.a} ${obj2.b}`); // writes 1 3 |
|||
</syntaxhighlight> |
|||
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore, they implement full [[closure (computer science)|closure]]s by remembering the outer function's local variables even after the outer function has exited. |
|||
<syntaxhighlight lang="javascript"> |
|||
let t = "Top"; |
|||
let bar, baz; |
|||
function foo() { |
|||
let f = "foo var"; |
|||
bar = function() { console.log(f) }; |
|||
baz = function(x) { f = x; }; |
|||
} |
|||
foo(); |
|||
baz("baz arg"); |
|||
bar(); // "baz arg" (not "foo var") even though foo() has exited. |
|||
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=== |
|||
{{excerpt|Async/await|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-based programming|prototype 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.). |
|||
===Creating objects=== |
|||
Objects can be created using a constructor or an object literal. The constructor can use either a built-in Object function or a custom function. It is a convention that constructor functions are given a name that starts with a capital letter: |
|||
<syntaxhighlight lang="javascript"> |
|||
// Constructor |
|||
const anObject = new Object(); |
|||
// Object literal |
|||
const objectA = {}; |
|||
const objectA2 = {}; // A != A2, {}s create new objects as copies. |
|||
const objectB = {index1: 'value 1', index2: 'value 2'}; |
|||
// Custom constructor (see below) |
|||
</syntaxhighlight> |
|||
Object literals and array literals allow one to easily create flexible data structures: |
|||
<syntaxhighlight lang="javascript"> |
|||
const myStructure = { |
|||
name: { |
|||
first: "Mel", |
|||
last: "Smith" |
|||
}, |
|||
age: 33, |
|||
hobbies: ["chess", "jogging"] |
|||
}; |
|||
</syntaxhighlight> |
|||
This is the basis for [[JSON]], which is a simple notation that uses JavaScript-like syntax for data exchange. |
|||
===Methods=== |
|||
A [[Method (computer programming)|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 initializes 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. |
|||
<syntaxhighlight lang="javascript"> |
|||
function px() { return this.prefix + "X"; } |
|||
function Foo(yz) { |
|||
this.prefix = "a-"; |
|||
if (yz > 0) { |
|||
this.pyz = function() { return this.prefix + "Y"; }; |
|||
} else { |
|||
this.pyz = function() { return this.prefix + "Z"; }; |
|||
} |
|||
this.m1 = px; |
|||
return this; |
|||
} |
|||
const foo1 = new Foo(1); |
|||
const foo2 = new Foo(0); |
|||
foo2.prefix = "b-"; |
|||
console.log("foo1/2 " + foo1.pyz() + foo2.pyz()); |
|||
// foo1/2 a-Y b-Z |
|||
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px() |
|||
const baz = {"prefix": "c-"}; |
|||
baz.m4 = px; // No need for a constructor to make an object. |
|||
console.log("m1/m3/m4 " + foo1.m1() + foo1.m3() + baz.m4()); |
|||
// m1/m3/m4 a-X a-X c-X |
|||
foo1.m2(); // Throws an exception, because foo1.m2 does not exist. |
|||
</syntaxhighlight> |
|||
===Constructors=== |
|||
[[Constructor function]]s simply assign values to slots of a newly created object. The values may be data or other functions. |
|||
Example: Manipulating an object: |
|||
<syntaxhighlight lang="javascript"> |
|||
function MyObject(attributeA, attributeB) { |
|||
this.attributeA = attributeA; |
|||
this.attributeB = attributeB; |
|||
} |
|||
MyObject.staticC = "blue"; // On MyObject Function, not object |
|||
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 |
|||
object.attributeC = new Date(); // add a new property |
|||
delete object.attributeB; // remove a property of object |
|||
// note that unlike C++, delete does not invoke a "destructor", |
|||
// but rather removes a property of an object. |
|||
console.log(object.attributeB); // undefined |
|||
</syntaxhighlight> |
|||
The constructor itself is referenced in the object's prototype's ''constructor'' slot. So, |
|||
<syntaxhighlight lang="javascript"> |
|||
function Foo() {} |
|||
// Use of 'new' sets prototype slots (for example, |
|||
// 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 initialized with |
|||
// {} instead of new Foo. |
|||
// Even though Foo is set to y's constructor slot, |
|||
// this is ignored by instanceof - only y's prototype's |
|||
// constructor slot is considered. |
|||
</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 <code>prototype</code> 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. |
|||
===Inheritance=== |
|||
JavaScript supports inheritance hierarchies through prototyping in the manner of [[Self (programming language)|Self]]. |
|||
In the following example, the {{mono|Derived}} class inherits from the {{mono|Base}} class. |
|||
When {{mono|d}} is created as {{mono|Derived}}, the reference to the base instance of {{mono|Base}} is copied to {{mono|d.base}}. |
|||
Derive does not contain a value for {{mono|aBaseFunction}}, so it is retrieved from {{mono|aBaseFunction}} ''when {{mono|aBaseFunction}} is accessed''. This is made clear by changing the value of {{mono|base.aBaseFunction}}, which is reflected in the value of {{mono|d.aBaseFunction}}. |
|||
Some implementations allow the prototype to be accessed or set explicitly using the {{mono|__proto__}} slot as shown below. |
|||
<syntaxhighlight lang="javascript"> |
|||
function Base() { |
|||
this.anOverride = function() { console.log("Base::anOverride()"); }; |
|||
this.aBaseFunction = function() { console.log("Base::aBaseFunction()"); }; |
|||
} |
|||
function Derived() { |
|||
this.anOverride = function() { console.log("Derived::anOverride()"); }; |
|||
} |
|||
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() |
|||
d.aBaseFunction(); // Base::aNEWBaseFunction() |
|||
console.log(d.aBaseFunction == Derived.prototype.aBaseFunction); // true |
|||
console.log(d.__proto__ == base); // true in Mozilla-based implementations and false in many others. |
|||
</syntaxhighlight> |
|||
The following shows clearly how references to prototypes are ''copied'' on instance creation, but that changes to a prototype can affect all instances that refer to it. |
|||
<syntaxhighlight lang="javascript"> |
|||
function m1() { return "One"; } |
|||
function m2() { return "Two"; } |
|||
function m3() { return "Three"; } |
|||
function Base() {} |
|||
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 |
|||
t.m = m1; // Does affect baz, and any other derived classes. |
|||
console.log("baz.m1 " + baz.m()); // baz.m1 One |
|||
</syntaxhighlight> |
|||
In practice many variations of these themes are used, and it can be both powerful and confusing. |
|||
==Exception handling== |
|||
JavaScript includes a <code>try ... catch ... finally</code> [[exception handling]] statement to handle run-time errors. |
|||
The <code>try ... catch ... finally</code> statement catches [[exception handling|exceptions]] resulting from an error or a throw statement. Its syntax is as follows: |
|||
<syntaxhighlight lang="javascript"> |
|||
try { |
|||
// Statements in which exceptions might be thrown |
|||
} catch (errorValue) { |
|||
// Statements that execute in the event of an exception |
|||
} finally { |
|||
// Statements that execute afterward either way |
|||
} |
|||
</syntaxhighlight> |
|||
Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. The catch block can {{mono|throw(errorValue)}}, if it does not want to handle a specific error. |
|||
In any case the statements in the finally block are always executed. Although memory is automatically garbage collected, this can be used to manually perform cleanup of resources (such as closing files or connections). |
|||
Either the catch or the finally clause may be omitted. The catch argument is required. |
|||
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in [[Java (programming language)|Java]]: |
|||
<syntaxhighlight lang="javascript"> |
|||
try { |
|||
statement; |
|||
} catch (e if e == "InvalidNameException") { |
|||
statement; |
|||
} catch (e if e == "InvalidIdException") { |
|||
statement; |
|||
} catch (e if e == "InvalidEmailException") { |
|||
statement; |
|||
} catch (e) { |
|||
statement; |
|||
} finally { |
|||
statement; |
|||
} |
|||
</syntaxhighlight> |
|||
In a browser, the {{mono|onerror}} event is more commonly used to trap exceptions. |
|||
<!-- This needs verification --> |
|||
<syntaxhighlight lang="javascript"> |
|||
onerror = function (errorValue, url, lineNr) {...; return true;}; |
|||
</syntaxhighlight> |
|||
==Native functions and methods== |
|||
===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() { |
|||
... var x = 7; |
|||
... console.log("val " + eval("x + 2")); |
|||
... })(); |
|||
val 9 |
|||
undefined |
|||
</syntaxhighlight> |
|||
==TypeScript-specific features== |
|||
[[TypeScript]], a superset of JavaScript developed by [[Microsoft]], adds the following syntax extensions to JavaScript: |
|||
* [[Type signature]]s (annotations) and [[compile-time]] [[type checking]] |
|||
* [[Type inference]] |
|||
* [[Interface (object-oriented programming)|Interfaces]] |
|||
* [[Enumerated type]]s |
|||
* [[Generic programming|Generics]] |
|||
* [[Namespace]]s |
|||
* [[Tuple]]s |
|||
* [[Resource management (computing)|Explicit resource management]]<ref name="5.2">{{Cite web |title=Documentation – TypeScript 5.2 |url=https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html |access-date=9 November 2023 |website=www.typescriptlang.org |language=en |archive-date=9 August 2024 |archive-url=https://web.archive.org/web/20240809080229/https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html |url-status=live}}</ref> |
|||
Syntactically, TypeScript is very similar to [[JScript .NET]], another Microsoft implementation of the ECMA-262 language standard that added support for static typing and classical object-oriented language features such as classes, inheritance, interfaces, and namespaces. Other inspirations include [[Java (programming language)|Java]] and [[C Sharp (programming language)|C#]]. |
|||
=== Type annotations === |
|||
TypeScript provides [[static typing]] through type annotations to enable [[type checking]] at [[compile time]]. |
|||
<syntaxhighlight lang="typescript"> |
|||
function add(left: number, right: number): number { |
|||
return left + right; |
|||
} |
|||
</syntaxhighlight> |
|||
Primitive types are annotated using all-lowercase types, such as <code>number</code>, <code>boolean</code>, <code>bigint</code>, and <code>string</code>. These types are distinct from their [[Boxing (computer programming)|boxed]] counterparts (<code>Number</code>, <code>Boolean</code>, etc.), which cannot have operations performed from values directly (a <code>Number</code> and <code>number</code> cannot be added). Also are <code>undefined</code> and <code>null</code> types for their respective values. |
|||
All other non-primitive types are annotated using their class name, such as <code>Error</code>. Arrays can be written in two different ways which are both syntactically the same: the generic-based syntax <code>Array<T></code> and a shorthand with <code>T[]</code>. |
|||
Further built-in data types are tuples, unions, <code>never</code>, <code>unknown</code>, <code>void</code>, and <code>any</code>: |
|||
* An array with predefined data types at each index is a tuple, represented as <code>[type1, type2, ..., typeN]</code>. |
|||
* A variable that can hold more than one type of data is a union, represented using the logical OR <code>|</code> symbol (<code>string | number</code>). |
|||
* The <code>never</code> type is used when a given type should be impossible to create, which is useful for filtering mapped types. |
|||
* The <code>unknown</code> type is used when dealing with data of an unpredictable shape. Unlike <code>any</code>, an <code>unknown</code>-typed variable will throw compilation errors when attempting to access properties or methods on that variable without first narrowing the type to something known. This type is often used for catching Errors, handling API responses, or user input.<ref>{{Cite web |title=Handbook - Basic Types |url=https://www.typescriptlang.org/docs/handbook/2/everyday-types.html |access-date=2025-07-02 |website=www.typescriptlang.org |language=en}}</ref> |
|||
* The <code>void</code> type is used to represent the lack of a type, e.g. from a function with no <code>return</code> statement. |
|||
* A value of type <code>any</code> supports the same operations as a value in JavaScript and minimal static type checking is performed,<ref>{{Cite web |title=TypeScript Language Specification p.24 |url=http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf |url-status=dead |archiveurl=https://web.archive.org/web/20131117065339/http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf |archivedate=17 November 2013}}</ref> which makes it suitable for weakly or dynamically typed structures. This is generally discouraged practice and should be avoided when possible.<ref name="TypeScript Language Specification">{{cite web|title=TypeScript: Documentation – Everyday Types|url=https://www.typescriptlang.org/docs/handbook/2/everyday-types.html|access-date=30 March 2021|website=www.typescriptlang.org|archive-date=9 August 2024|archive-url=https://web.archive.org/web/20240809080104/https://www.typescriptlang.org/docs/handbook/2/everyday-types.html|url-status=live}}</ref> |
|||
Type annotations can be exported to a separate ''declarations file'' to make type information available for TypeScript scripts using types already compiled into JavaScript. Annotations can be declared for an existing JavaScript library, as has been done for [[Node.js]] and [[jQuery]]. |
|||
The TypeScript compiler makes use of [[type inference]] when types are not given. For example, the <code>add</code> method in the code above would be inferred as returning a <code>number</code> even if no return type annotation had been provided. This is based on the static types of <code>left</code> and <code>right</code> being <code>number</code>s, and the compiler's knowledge that the result of adding two <code>number</code>s is always a <code>number</code>. |
|||
If no type can be inferred because of lack of declarations (such as in a JavaScript module without types), then it defaults to the dynamic <code>any</code> type. Additional module types can be provided using a .d.ts declaration file using the <code>declare module "moduleName"</code> syntax. |
|||
=== Declaration files === |
|||
When a TypeScript script gets compiled, there is an option to generate a ''declaration file'' (with the extension <code>.d.ts</code>) that functions as an [[interface (computing)|interface]] to the components in the compiled JavaScript. In the process, the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript. |
|||
The concept of declaration files is analogous to the concept of [[header file]]s found in [[C/C++]]. |
|||
<syntaxhighlight lang="typescript"> |
|||
declare namespace Arithmetics { |
|||
add(left: number, right: number): number; |
|||
subtract(left: number, right: number): number; |
|||
multiply(left: number, right: number): number; |
|||
divide(left: number, right: number): number; |
|||
} |
|||
</syntaxhighlight> |
|||
Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js. |
|||
Large collections of declaration files for popular JavaScript libraries are hosted on [[GitHub]] in [https://github.com/DefinitelyTyped/DefinitelyTyped DefinitelyTyped]. |
|||
=== Generics === |
|||
{{Further|Generic programming}} |
|||
TypeScript supports [[generic programming]] using a syntax similar to [[Java (programming language)|Java]].<ref>{{cite web |last1=Turner |first1=Jonathan |date=18 June 2013 |title=Announcing TypeScript 0.9 |url=http://blogs.msdn.com/b/typescript/archive/2013/06/18/announcing-typescript-0-9.aspx |work=TypeScript Language team blog |publisher=[[Microsoft]] |access-date=18 June 2013 |archive-date=26 November 2013 |archive-url=https://web.archive.org/web/20131126093545/http://blogs.msdn.com/b/typescript/archive/2013/06/18/announcing-typescript-0-9.aspx |url-status=live}}</ref> The following is an example of the [[identity function]].<ref>{{cite web |title=Generics in Typescript |url=https://www.typescriptlang.org/docs/handbook/generics.html#working-with-generic-type-variables |publisher=[[Microsoft]] |access-date=8 April 2020 |archive-date=5 April 2020 |archive-url=https://web.archive.org/web/20200405180639/https://www.typescriptlang.org/docs/handbook/generics.html#working-with-generic-type-variables |url-status=live}}</ref> |
|||
<syntaxhighlight lang="typescript"> |
|||
function identity<T>(x: T): T { |
|||
return x; |
|||
} |
|||
</syntaxhighlight> |
|||
Similar to [[Generics in Java|Java generics]], it is possible to bound a type parameter: |
|||
<syntaxhighlight lang="typescript"> |
|||
function f<T extends string>(x: T): void { |
|||
// ... |
|||
} |
|||
function prop<T, K extends keyof T>(obj: T, key: K): T[K] { |
|||
return obj[key]; |
|||
} |
|||
</syntaxhighlight> |
|||
Also, like C++, it is possible to have default generics parameters. |
|||
<syntaxhighlight lang="typescript"> |
|||
function makeArray<T = number>(value: T): T[] { |
|||
return [value]; |
|||
} |
|||
</syntaxhighlight> |
|||
=== Classes === |
|||
TypeScript uses the same annotation style for class methods and fields as for functions and variables respectively. Compared with vanilla JavaScript classes, a TypeScript class can also implement an interface through the <code>implements</code> keyword, use generic parameters similarly to [[Java (programming language)|Java]], and specify public and private fields. |
|||
<syntaxhighlight lang="typescript"> |
|||
class Person { |
|||
public name: string; |
|||
private age: number; |
|||
private salary: number; |
|||
constructor(name: string, age: number, salary: number) { |
|||
this.name = name; |
|||
this.age = age; |
|||
this.salary = salary; |
|||
} |
|||
toString(): string { |
|||
return `${this.name} (${this.age}) (${this.salary})`; |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=== Union types === |
|||
{{excerpt|Union type|TypeScript}} |
|||
=== Enumerated types === |
|||
{{excerpt|Enumerated type|TypeScript|subsections=yes}} |
|||
=== Modules and namespaces === |
|||
TypeScript distinguishes between modules and namespaces, similar to [[Modules (C++)|C++ modules]]. Both features in TypeScript support encapsulation of classes, interfaces, functions and variables into containers. Namespaces (formerly internal modules) use JavaScript [[immediately-invoked function expression]]s to encapsulate code, whereas modules (formerly external modules) use existing JavaScript library patterns ([[CommonJS]] or ES Modules).<ref>{{cite web |url=http://blog.oio.de/2014/01/31/an-introduction-to-typescript-module-system/ |title=An introduction to TypeScript's module system |publisher=blog.oio.de |date=31 January 2014 |last1=Sothmann |first1=Sönke |access-date=21 February 2014 |archive-date=1 February 2014 |archive-url=https://web.archive.org/web/20140201102512/http://blog.oio.de/2014/01/31/an-introduction-to-typescript-module-system/ |url-status=dead}}</ref> |
|||
=== Resource management === |
|||
Although TypeScript does not have manual memory management, it has resource management similar to <code>using</code>-with-resource blocks in [[C Sharp (programming language)|C#]] or <code>try</code>-with-resources blocks in [[Java (programming language)|Java]], or [[C++]] [[resource acquisition is initialization]], that automatically close resources without need for <code>finally</code> blocks. In TypeScript, to automatically close an object, it must implement a global interface <code>Disposable</code>, and implement a method <code>Symbol.dispose()</code>. This will automatically be called at the end of scope.<ref name="5.2"/> |
|||
<syntaxhighlight lang=TypeScript> |
|||
import * as fs from 'fs'; |
|||
class TempFile implements Disposable { |
|||
#path: string; |
|||
#handle: number; |
|||
constructor(path: string) { |
|||
this.#path = path; |
|||
this.#handle = fs.openSync(path, "w+"); |
|||
} |
|||
write(data: string): void { |
|||
fs.writeSync(this.#handle, data); |
|||
} |
|||
[Symbol.dispose](): void { |
|||
fs.closeSync(this.#handle); |
|||
fs.unlinkSync(this.#path); |
|||
} |
|||
} |
|||
export function doSomeWork() { |
|||
using file: TempFile = new TempFile(".some_temp_file.txt"); |
|||
if (someCondition()) { |
|||
// do something here |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
==See also== |
|||
* [[JavaScript]] |
|||
* [[Java syntax]] |
|||
* [[C syntax]] |
|||
* [[C++ syntax]] |
|||
==References== |
|||
{{Reflist}} |
|||
==Further reading== |
|||
* Danny Goodman: ''JavaScript Bible'', Wiley, John & Sons, {{ISBN|0-7645-3342-8}}. |
|||
* David Flanagan, Paula Ferguson: ''JavaScript: The Definitive Guide'', O'Reilly & Associates, {{ISBN|0-596-10199-6}}. |
|||
* Thomas A. Powell, Fritz Schneider: ''JavaScript: The Complete Reference'', McGraw-Hill Companies, {{ISBN|0-07-219127-9}}. |
|||
* Axel Rauschmayer: ''Speaking JavaScript: An In-Depth Guide for Programmers'', 460 pages, O'Reilly Media, 25 February 2014, {{ISBN|978-1449365035}}. ([http://speakingjs.com/ free online edition]) |
|||
* Emily Vander Veer: ''JavaScript For Dummies, 4th Edition'', Wiley, {{ISBN|0-7645-7659-3}}. |
|||
==External links== |
|||
{{Wikibooks|JavaScript}} |
|||
* [https://developer.mozilla.org/en/docs/A_re-introduction_to_JavaScript A re-introduction to JavaScript - Mozilla Developer Center] |
|||
* [https://codetopology.com/category/scripts/javascript-tutorials/ JavaScript Loops] |
|||
* 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] |
|||
* [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/ 1.4], [https://web.archive.org/web/20070210000504/http://research.nihonsoft.org/javascript/ClientReferenceJS13/ 1.3] and [https://web.archive.org/web/20070210000545/http://research.nihonsoft.org/javascript/jsref/ 1.2] |
|||
* [https://developer.mozilla.org/en/docs/JavaScript Mozilla JavaScript Language Documentation] |
|||
{{JavaScript}} |
|||
{{DEFAULTSORT:Javascript Syntax}} |
|||
[[Category:JavaScript|syntax]] |
|||
[[Category:Programming language syntax]] |
|||
<!-- Hidden categories below --> |
|||
[[Category:Articles with example JavaScript code]] |
|||
Latest revision as of 00:30, 25 October 2026
This article needs to be updated. The reason given is: Rewrite the article to be less tutorial-like and more primarily focused on syntax/features. (November 2020) |

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.
The examples below make use of the console.log() function present in most browsers for standard text output.
The JavaScript standard library lacks an official standard text output function (with the exception of document.write). Given that JavaScript is mainly used for client-side scripting within modern web browsers, and that almost all web browsers provide the alert function, alert can also be used, but it is not commonly used.
TypeScript, which extends JavaScript with type annotations and additional features, has the same syntax as well as its own additional features.
Origins
[edit | edit source]
Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification[1][2] as follows:
JavaScript borrows most of its syntax from Java, but also inherits from Awk and Perl, with some indirect influence from Self in its object prototype system.
JavaScript syntax is mostly derived from Java syntax, which in turn is derived from C syntax and C++ syntax.
Basics
[edit | edit source]Keywords
[edit | edit source]Reserved keywords
[edit | edit source]The following words are keywords:
breakcasecatchclassconstcontinuedebuggerdefaultdeletedoelseenumevalexportextendsfinallyforfunctionifimportininstanceofnewreturnsuperswitchthisthrowtrytypeofusingvarvoidwhilewith
Reserved keywords in strict mode
[edit | edit source]The following words are keywords in strict mode:
letimplementsinterfacestaticpackageprivateprotectedpublicyield
Reserved keywords in module code or async function body
[edit | edit source]The following words are keywords in module code or async function body:
await
Literal values
[edit | edit source]The following words refer to literal values used by the language:
truefalsenull
JavaScript also defines the following global constants, which are not keywords:
NaNInfinityundefined
Removed keywords
[edit | edit source]The following words, primarily associated with Java, were removed from the ECMAScript 5/6 standard:
abstractbooleanbytechardoublefinalfloatgotointlongnativeshortsynchronizedthrowstransientvolatile
TypeScript keywords
[edit | edit source]The additional following words are keywords in TypeScript:
abstractanyasdeclareinferkeyofmodulenamespaceneverreadonlytypeunknown
Case sensitivity
[edit | edit source]JavaScript is case sensitive. It is common to start the name of a constructor with a capitalized letter, and the name of a function or variable with a lower-case letter.
Example:
var a = 5;
console.log(a); // 5
console.log(A); // throws a ReferenceError: A is not defined
Whitespace and semicolons
[edit | edit source]Unlike in C, whitespace in JavaScript source can directly impact semantics. Semicolons end statements in JavaScript. Because of automatic semicolon insertion (ASI), some statements that are well formed when a newline is 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.[3]
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.
The five problematic tokens are the open parenthesis "(", open bracket "[", slash "/", plus "+", and minus "-". Of these, the open parenthesis is common in the immediately invoked function expression pattern, and open bracket occurs sometimes, while others are quite rare. An example:
a = b + c
(d + e).foo()
// Treated as:
// a = b + c(d + e).foo();
with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use of leading semicolons on lines starting with '(' or '[', so the line is not accidentally joined with the previous one. This is known as a defensive semicolon, and is employed because code may otherwise become ambiguous when it is rearranged. For example:
a = b + c
;(d + e).foo()
// Treated as:
// a = b + c;
// (d + e).foo();
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. In such a case where perhaps unusual semicolon placement occurs, it may just be better to manually place semicolons at the end of statements.
The five restricted productions are return, throw, break, continue, 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. return and throw take an optional value, while break and continue 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.
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
// Should be written as:
// return a + b;
Comments
[edit | edit source]Comment syntax is the same as in C, C++ and other programming languages.
Single-line comments begin with // and continue until the end of the line. Multi-line comments start with /* and end with */ , and can span multiple lines.
A third type of comment, the hashbang comment, starts with #! and continues until the end of the line. They are only valid at the start of files and are intended for use in CLI environments.[4]
#! Hashbang comment
// One-line comment
/* Multi-line
comment */
Variables
[edit | edit source]Variables in standard JavaScript have no type attached, so any value (each value has a type) can be stored in any variable. Starting with ES6, the 6th version of the language, variables could be declared with var for function scoped variables, and let or const which are for block level variables. Before ES6, variables could only be declared with a var statement. Values assigned to variables declared with const cannot be changed, but their properties can. var should no longer be used since let and const are supported by modern browsers.[5] A variable's identifier must start with a letter, underscore (_), or dollar sign ($), while subsequent characters can also be digits (0-9). 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 \uXXXX Unicode escape sequences) can be used in identifiers.[6] 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]
Scoping and hoisting
[edit | edit source]Variables declared with var are lexically scoped at a function level, while ones with let or const have a 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.[7] This is referred to as hoisting, and it is equivalent to variables being forward declared at the top of the function or block.[8]
With var, let, and const statements, only the declaration is hoisted; assignments are not hoisted. Thus a var x = 1 statement in the middle of the function is equivalent to a var x declaration statement at the top of the function, and an 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 var a variable's value is undefined until it is initialized. Variables declared with let or const cannot be accessed until they have been initialized, so referencing such variables before will cause an error.
Function declarations, which declare a variable and assign a function to it, 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 var, let, or const statement.
So, for example,
var func = function() { .. } // declaration is hoisted only
function func() { .. } // declaration and assignment are hoisted
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 let keyword.
Declaration and assignment
[edit | edit source]Variables declared outside a scope are global. If a variable is declared in a higher scope, it can be accessed by child scopes.
When JavaScript tries to resolve an identifier, it looks in the local scope. If this identifier is not found, it looks in the next outer scope, 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 ReferenceError 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" in the scope where it was created.[9] As a consequence, a variable never declared will be global, if assigned. Declaring a variable (with the keyword var) in the global scope (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.
Examples
[edit | edit source]Here are some examples of variable declarations and scope:
var x1 = 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 was not declared anywhere before
function child() {
var r = 'monkeys'; // This variable is local and does not affect the "birds" r of the parent function.
z = 'penguins'; // Closure: Child function is able to access the variables of the parent function.
}
twenty = 20; // This variable is declared on the next line, but usable anywhere in the function, even before, as here
var twenty;
child();
return x1 + x2; // We can use x1 and x2 here, because they are global
}
f();
console.log(z); // This line will raise a ReferenceError exception, because the value of z is no longer available
for (let i = 0; i < 10; i++) console.log(i);
console.log(i); // throws a ReferenceError: i is not defined
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
Primitive data types
[edit | edit source]The JavaScript language provides six primitive data types:
UndefinedNumberBigIntStringBooleanSymbol
Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries. These named values are described within the appropriate sections below.
Undefined
[edit | edit source]The value of "undefined" is assigned to all uninitialized variables, 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.
Note: undefined is considered a genuine primitive type. Unless explicitly converted, the undefined value may behave unexpectedly in comparison to other types that evaluate to false in a logical context.
let test; // variable declared, but not defined, ...
// ... set to value of undefined
const testObj = {};
console.log(test); // test variable exists, but value not ...
// ... defined, displays undefined
console.log(testObj.myProp); // testObj exists, property does not, ...
// ... displays undefined
console.log(undefined == null); // unenforced type during check, displays true
console.log(undefined === null); // enforce type during check, displays false
Note: There is no built-in language literal for undefined. Thus (x === undefined) is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it was legal to write var undefined = "I'm defined now";. A more robust approach is to compare using (typeof x === 'undefined').
Functions like this will not work as expected:
function isUndefined(x) { let 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
Here, calling isUndefined(my_var) raises a ReferenceError if my_var is an unknown identifier, whereas typeof my_var === 'undefined' does not.
Number
[edit | edit source]Numbers are represented in binary as IEEE 754 floating point doubles. Although this format provides an accuracy of nearly 16 significant digits, it cannot always exactly represent real numbers, including fractions.
This becomes an issue when comparing or formatting numbers. For example:
console.log(0.2 + 0.1 === 0.3); // displays false
console.log(0.94 - 0.01); // displays 0.9299999999999999
As a result, a routine such as the toFixed() method should be used to round numbers whenever they are formatted for output.
Numbers may be specified in any of these notations:
345; // an "integer", although there is only one numeric type in JavaScript
34.5; // a floating-point number
3.45e2; // another floating-point, equivalent to 345
0b1011; // a binary integer equal to 11
0o377; // an octal integer equal to 255
0xFF; // a hexadecimal integer equal to 255, digits represented by the ...
// ... letters A-F may be upper or lowercase
There is also a numeric separator, _ (the underscore), introduced in ES2021:
// Note: Wikipedia syntax doesn't 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
The extents +∞, −∞ and NaN (Not a Number) of the number type may be obtained by two to three (including −∞) program expressions:
Infinity; // positive infinity
-Infinity; // negative infinity (not its own expression, just Infinity but negative)
NaN; // The Not-A-Number value, also returned as a failure in ...
// ... string-to-number conversions
Infinity and NaN are numbers:
typeof Infinity; // returns "number"
typeof NaN; // returns "number"
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:
const myString = "123.456";
const myNumber1 = Number(myString);
const myNumber2 = +myString;
When used as a constructor, a numeric wrapper object is created (though it is of little use):
const myNumericWrapper = new Number(123.456);
However, NaN is not equal to itself:
const nan = NaN;
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(NaN !== NaN); // true
console.log(nan !== nan); // true
// The isNaN methods can be used to check for NaN
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
BigInt
[edit | edit source]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 Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER.[10] BigInts instead represent integers of any size, allowing programmers to store integers too high or low to be represented with the IEEE 754 format.[11]
There are two ways to declare a BigInt value: an n can be appended to an integer, or the BigInt function can be used:[11]
const a = 12345n; // Creates a variable and stores a BigInt value of 12345
const b = BigInt(12345); // Also does that using the BigInt function instead
String
[edit | edit source]A string in JavaScript is a sequence of characters. In JavaScript, strings can be created directly (as literals) by placing the series of characters between double (") or single (') quotes. Such strings must be written on a single line, but may include escaped newline characters (such as \n). The JavaScript standard allows the backquote character (`, a.k.a. grave accent or backtick) to quote multiline literal strings, as well as embedded expressions using the syntax ${expression}.[12]
const greeting = "Hello, World!";
const anotherGreeting = 'Greetings, people of Earth.';
const aMultilineGreeting = `Warm regards,
John Doe.`
// Template literals type-coerce evaluated expressions and interpolate them into the string.
const templateLiteral = `This is what is stored in anotherGreeting: ${anotherGreeting}.`;
console.log(templateLiteral); // 'This is what is stored in anotherGreeting: 'Greetings, people of Earth.''
console.log(`You are ${Math.floor(age)=>18 ? "allowed" : "not allowed"} to view this web page`);
Individual characters within a string can be accessed using the charAt method (provided by String.prototype). This is the preferred way when accessing individual characters within a string, because it also works in non-modern browsers:
const h = greeting.charAt(0);
In modern browsers, individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays:
const h = greeting[0];
However, JavaScript strings are immutable:
greeting[0] = "H"; // Fails
Applying the equality operator ("==") to two strings returns true, if the strings have the same contents, which means: of the same length and containing the same sequence of characters (case is significant for alphabets). Thus:
const x = "World";
const compare1 = ("Hello, " + x == "Hello, World"); // Here compare1 contains true.
const compare2 = ("Hello, " + x == "hello, World"); // Here compare2 contains ...
// ... false since the ...
// ... first characters ...
// ... of both operands ...
// ... are not of the same case.
Quotes of the same type cannot be nested unless they are escaped.
let x = '"Hello, World!" he said.'; // Just fine
x = ""Hello, World!" he said."; // Not good
x = "\"Hello, World!\" he said."; // Works by escaping " with \"
The String constructor creates a string object (an object wrapping a string):
const greeting = new String("Hello, World!");
These objects have a valueOf method returning the primitive string wrapped within them:
const s = new String("Hello !");
typeof s; // Is 'object'
typeof s.valueOf(); // Is 'string'
Equality between two String objects does not behave as with string primitives:
const s1 = new String("Hello !");
const s2 = new String("Hello !");
s1 == s2; // Is false, because they are two distinct objects
s1.valueOf() == s2.valueOf(); // Is true
Boolean
[edit | edit source]JavaScript provides a Boolean data type with true and false literals. The typeof operator returns the string "boolean" for these primitive types. When used in a logical context, 0, -0, null, NaN, undefined, and the empty string ("") evaluate as false due to automatic type conversion. All other values (the complement of the previous list) evaluate as true, including the strings "0", "false" and any object.
Type conversion
[edit | edit source]Automatic type coercion by the equality comparison operators (== and !=) can be avoided by using the type checked comparison operators (=== and !==).
When type conversion is required, JavaScript converts Boolean, Number, String, or Object operands as follows:[13]
- 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.
- Boolean
- If one of the operands is a Boolean, the Boolean operand is converted to 1 if it is true, or to 0 if it is false.
- 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 .valueOf() or .toString() methods of the object. If this fails, a runtime error is generated.
Boolean type conversion
[edit | edit source]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.[14]
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 : false, in the case of conjunction: (a && b), or true, in the case of disjunction: (a || b); 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 operator: (!!), using the Boolean() function, or using the conditional operator: (c ? t : f).
// Automatic type coercion
console.log(true == 2 ); // false... true → 1 !== 2 ← 2
console.log(false == 2 ); // false... false → 0 !== 2 ← 2
console.log(true == 1 ); // true.... true → 1 === 1 ← 1
console.log(false == 0 ); // true.... false → 0 === 0 ← 0
console.log(true == "2"); // false... true → 1 !== 2 ← "2"
console.log(false == "2"); // false... false → 0 !== 2 ← "2"
console.log(true == "1"); // true.... true → 1 === 1 ← "1"
console.log(false == "0"); // true.... false → 0 === 0 ← "0"
console.log(false == "" ); // true.... false → 0 === 0 ← ""
console.log(false == NaN); // false... false → 0 !== NaN
console.log(NaN == NaN); // false...... NaN is not equivalent to anything, including NaN.
// Type checked comparison (no conversion of types and values)
console.log(true === 1); // false...... data types do not match
// Explicit type coercion
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" numbers
console.log("0" ? true : false); // true.... only the empty string is "falsy"
console.log(Boolean({})); // true.... all objects are "truthy"
The new operator can be used to create an object wrapper for a Boolean primitive. However, the typeof operator does not return boolean for the object wrapper, it returns object. Because all objects evaluate as true, a method such as .valueOf(), or .toString(), must be used to retrieve the wrapped value. For explicit coercion to the Boolean type, Mozilla recommends that the Boolean() function (without new) be used in preference to the Boolean object.
const b = new Boolean(false); // Object false {}
const t = Boolean(b); // Boolean true
const f = Boolean(b.valueOf()); // Boolean false
let n = new Boolean(b); // Not recommended
n = new Boolean(b.valueOf()); // Preferred
if (0 || -0 || "" || null || undefined || b.valueOf() || !new Boolean() || !t) {
console.log("Never this");
} else if ([] && {} && b && typeof b === "object" && b.toString() === "false") {
console.log("Always this");
}
Symbol
[edit | edit source]Symbols are a feature introduced in ES6. Each symbol is guaranteed to be a unique value, and they can be used for encapsulation.[15]
Example:
let x = Symbol(1);
const y = Symbol(1);
x === y; // => false
const symbolObject = {};
const normalObject = {};
// since x and y are unique,
// they can be used as unique keys in an object
symbolObject[x] = 1;
symbolObject[y] = 2;
symbolObject[x]; // => 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
There are also well known symbols.
One of which is Symbol.iterator; if something implements Symbol.iterator, it is iterable:
const x = [1, 2, 3, 4]; // x is an Array
x[Symbol.iterator] === Array.prototype[Symbol.iterator]; // and Arrays are iterable
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"
}
Native objects
[edit | edit source]The JavaScript language provides a handful of native objects. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available.
Array
[edit | edit source]An Array is a JavaScript object prototyped from the Array 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, join, slice, and push).
As in the C family, arrays use a zero-based indexing scheme: A value that is inserted into an empty array by means of the push method occupies the 0th index of the array.
const 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");
Arrays have a length 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 length property will remove larger indices.
Elements of Arrays may be accessed using normal object property access notation:
myArray[1]; // the 2nd item in myArray
myArray["1"];
The above two are equivalent. It is not possible to use the "dot"-notation or strings with alternative representations of the number:
myArray.1; // syntax error
myArray["01"]; // not the same as myArray[1]
Declaration of an array can use either an Array literal or the Array constructor:
let myArray;
// Array literals
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
Arrays are implemented so that only the defined elements use memory; they are "sparse arrays". Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements, just like any other object. The length 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)2.
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
const dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both. (Technically, JavaScript does not support multidimensional arrays, but one can mimic them with arrays-of-arrays.)
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"
dogs.rover.color; // results in "brown"
Date
[edit | edit source]A Date object stores a signed millisecond count with zero representing 1970-01-01 00:00:00 UT and a range of ±108 days. There are several ways of providing arguments to the Date constructor. Note that months are zero-based.
new Date(); // create a new Date instance representing the current time/date.
new Date(2010, 2, 1); // create a new Date instance representing 2010-Mar-01 00:00:00
new Date(2010, 2, 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.
Methods to extract fields are provided, as well as a useful toString:
const d = new Date(2010, 2, 1, 14, 25, 30); // 2010-Mar-01 14:25:30;
// Displays '2010-3-1 14:25:30':
console.log(d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' '
+ d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds());
// Built-in toString returns something like 'Mon 1 March, 2010 14:25:30 GMT-0500 (EST)':
console.log(d);
Error
[edit | edit source]Custom error messages can be created using the Error class:
throw new Error("Something went wrong.");
These can be caught by try...catch...finally blocks as described in the section on exception handling.
Math
[edit | edit source]The Math object contains various math-related constants (for example, π) and functions (for example, cosine). (Note that the Math object has no constructor, unlike Array or Date. All its methods are "static", that is "class" methods.) All the trigonometric functions use angles expressed in radians, not degrees or grads.
| Property | Returned value rounded to 5 digits | Description |
|---|---|---|
| Math.E | 2.7183 | e: Natural logarithm base |
| Math.LN2 | 0.69315 | Natural logarithm of 2 |
| Math.LN10 | 2.3026 | Natural logarithm of 10 |
| Math.LOG2E | 1.4427 | Logarithm to the base 2 of e |
| Math.LOG10E | 0.43429 | Logarithm to the base 10 of e |
| Math.PI | 3.14159 | π: circumference/diameter of a circle |
| Math.SQRT1_2 | 0.70711 | Square root of ½ |
| Math.SQRT2 | 1.4142 | Square root of 2 |
| Example | Returned value rounded to 5 digits | Description |
|---|---|---|
| Math.abs(-2.3) | 2.3 | Absolute value |
| Math.acos(Math.SQRT1_2) | 0.78540 rad = 45° | Arccosine |
| Math.asin(Math.SQRT1_2) | 0.78540 rad = 45° | Arcsine |
| Math.atan(1) | 0.78540 rad = 45° | Half circle arctangent ( to ) |
| Math.atan2(-3.7, -3.7) | −2.3562 rad = −135° | Whole circle arctangent ( to ) |
| Math.ceil(1.1) | 2 | Ceiling: round up to smallest integer ≥ argument |
| Math.cos(Math.PI/4) | 0.70711 | Cosine |
| Math.exp(1) | 2.7183 | Exponential function: e raised to this power |
| Math.floor(1.9) | 1 | Floor: round down to largest integer ≤ argument |
| Math.log(Math.E) | 1 | Natural logarithm, base e |
| Math.max(1, -2) | 1 | Maximum: (x > y) ? x : y |
| Math.min(1, -2) | −2 | Minimum: (x < y) ? x : y |
| Math.pow(-3, 2) | 9 | Exponentiation (raised to the power of): Math.pow(x, y) gives xy |
| Math.random() | e.g. 0.17068 | Pseudorandom number between 0 (inclusive) and 1 (exclusive) |
| Math.round(1.5) | 2 | Round to the nearest integer; half fractions are rounded up (e.g. 1.5 rounds to 2) |
| Math.sin(Math.PI/4) | 0.70711 | Sine |
| Math.sqrt(49) | 7 | Square root |
| Math.tan(Math.PI/4) | 1 | Tangent |
Regular expression
[edit | edit source]/expression/.test(string); // returns Boolean
"string".search(/expression/); // returns position Number
"string".replace(/expression/, replacement);
// Here are some examples
if (/Tom/.test("My name is Tom")) console.log("Hello Tom!");
console.log("My name is Tom".search(/Tom/)); // == 11 (characters before Tom)
console.log("My name is Tom".replace(/Tom/, "John")); // == "My name is John"
Character classes
[edit | edit source]// \d - digit
// \D - non digit
// \s - space
// \S - non space
// \w - word char
// \W - non word
// [ ] - one of
// [^] - one not of
// - - range
if (/\d/.test('0')) console.log('Digit');
if (/[0-9]/.test('6')) console.log('Digit');
if (/[13579]/.test('1')) console.log('Odd number');
if (/\S\S\s\S\S\S\S/.test('My name')) console.log('Format OK');
if (/\w\w\w/.test('Tom')) console.log('Hello Tom');
if (/[a-zA-Z]/.test('B')) console.log('Letter');
Character matching
[edit | edit source]// A...Z a...z 0...9 - alphanumeric
// \u0000...\uFFFF - Unicode hexadecimal
// \x00...\xFF - ASCII hexadecimal
// \t - tab
// \n - new line
// \r - CR
// . - any character
// | - OR
if (/T.m/.test('Tom')) console.log ('Hi Tom, Tam or Tim');
if (/A|B/.test("A")) console.log ('A or B');
Repeaters
[edit | edit source]// ? - 0 or 1 match
// * - 0 or more
// + - 1 or more
// {n} - exactly n
// {n,} - n or more
// {0,n} - n or less
// {n,m} - range n to m
if (/ab?c/.test("ac")) console.log("OK"); // match: "ac", "abc"
if (/ab*c/.test("ac")) console.log("OK"); // match: "ac", "abc", "abbc", "abbbc" etc.
if (/ab+c/.test("abc")) console.log("OK"); // match: "abc", "abbc", "abbbc" etc.
if (/ab{3}c/.test("abbbc")) console.log("OK"); // match: "abbbc"
if (/ab{3,}c/.test("abbbc")) console.log("OK"); // match: "abbbc", "abbbbc", "abbbbbc" etc.
if (/ab{1,3}c/.test("abc")) console.log("OK"); // match: "abc", "abbc", "abbbc"
Anchors
[edit | edit source]// ^ - string starts with
// $ - string ends with
if (/^My/.test("My name is Tom")) console.log ("Hi!");
if (/Tom$/.test("My name is Tom")) console.log ("Hi Tom!");
Subexpression
[edit | edit source]// ( ) - groups characters
if (/water(mark)?/.test("watermark")) console.log("Here is water!"); // match: "water", "watermark",
if (/(Tom)|(John)/.test("John")) console.log("Hi Tom or John!");
Flags
[edit | edit source]// /g - global
// /i - ignore upper/lower case
// /m - allow matches to span multiple lines
console.log("hi tom!".replace(/Tom/i, "John")); // == "hi John!"
console.log("ratatam".replace(/ta/, "tu")); // == "ratutam"
console.log("ratatam".replace(/ta/g, "tu")); // == "ratutum"
Advanced methods
[edit | edit source]my_array = my_string.split(my_delimiter);
// example
my_array = "dog,cat,cow".split(","); // my_array==["dog","cat","cow"];
my_array = my_string.match(my_expression);
// example
my_array = "We start at 11:30, 12:15 and 16:45".match(/\d\d:\d\d/g); // my_array==["11:30","12:15","16:45"];
Capturing groups
[edit | edit source]const myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;
const results = myRe.exec("The date and time are 2009-09-08 09:37:08.");
if (results) {
console.log("Matched: " + results[0]); // Entire match
const my_date = results[1]; // First group == "2009-09-08"
const 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!");
Function
[edit | edit source]Every function in JavaScript is an instance of the Function constructor:
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
const add = new Function('x', 'y', 'return x + y');
add(1, 2); // => 3
The add function above may also be defined using a function expression:
const add = function(x, y) {
return x + y;
};
add(1, 2); // => 3
In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain the this of the global object instead of inheriting it from where it was called / what it was called on, unlike the function() {} expression.
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
For functions that need to be hoisted, there is a separate expression:
function add(x, y) {
return x + y;
}
add(1, 2); // => 3
Hoisting allows users to use the function before it is "declared":
add(1, 2); // => 3, not a ReferenceError
function add(x, y) {
return x + y;
}
A function instance has properties and methods.
function subtract(x, y) {
return x - y;
}
console.log(subtract.length); // => 2, arity of the function (number of arguments)
console.log(subtract.toString());
/*
"function subtract(x, y) {
return x - y;
}"
*/
Operators
[edit | edit source]The '+' operator is overloaded: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number.
// Concatenate 2 strings
console.log('He' + 'llo'); // displays Hello
// Add two numbers
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
console.log('$' + (3 + 4)); // displays $7
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
Similarly, the '*' operator is overloaded: it can convert a string into a number.
console.log(2 + '6'*1); // displays 8
console.log(3*'7'); // 21
console.log('3'*'7'); // 21
console.log('hello'*'world'); // displays NaN
Arithmetic
[edit | edit source]JavaScript supports the following binary arithmetic operators:
+ | addition |
- | subtraction |
* | multiplication |
/ | division (returns a floating-point value) |
% | modulo (returns the remainder) |
** | exponentiation |
JavaScript supports the following unary arithmetic operators:
+ | unary conversion of string to number |
- | unary negation (reverses the sign) |
++ | increment (can be prefix or postfix) |
-- | decrement (can be prefix or postfix) |
let x = 1;
console.log(++x); // x becomes 2; displays 2
console.log(x++); // displays 2; x becomes 3
console.log(x); // x is 3; displays 3
console.log(x--); // displays 3; x becomes 2
console.log(x); // displays 2; x is 2
console.log(--x); // x becomes 1; displays 1
The modulo operator displays the remainder after division by the modulus. If negative numbers are involved, the returned value depends on the operand.
const x = 17;
console.log(x%5); // displays 2
console.log(x%6); // displays 5
console.log(-x%5); // displays -2
console.log(-x%-5); // displays -2
console.log(x%-5); // displays 2
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again:
const x = 17;
console.log((-x%5+5)%5); // displays 3
Users could also do:
const x = 17;
console.log(Math.abs(-x%5)); // also 3
Assignment
[edit | edit source]= | assign |
+= | add and assign |
-= | subtract and assign |
*= | multiply and assign |
/= | divide and assign |
%= | modulo and assign |
**= | exponentiation and assign |
let x = 9;
x += 1;
console.log(x); // displays: 10
x *= 30;
console.log(x); // displays: 300
x /= 6;
console.log(x); // displays: 50
x -= 3;
console.log(x); // displays: 47
x %= 7;
console.log(x); // displays: 5
Assignment of object types
/**
* To learn JavaScript objects...
*/
const object_1 = {a: 1}; // assign reference of newly created object to object_1
let object_2 = {a: 0};
let object_3 = object_2; // object_3 references the same object as object_2 does
object_3.a = 2;
message(); // displays 1 2 2
object_2 = object_1; // object_2 now references the same object as object_1
// object_3 still references what object_2 referenced before
message(); // displays 1 1 2
object_2.a = 7; // modifies object_1
message(); // displays 7 7 2
object_3.a = 5; // object_3 does not change object_2
message(); // displays 7 7 5
object_3 = object_2;
object_3.a=4; // object_3 changes object_1 and object_2
message(); // displays 4 4 4
/**
* Prints the console.log message
*/
function message() {
console.log(object_1.a + " " + object_2.a + " " + object_3.a);
}
Destructuring assignment
[edit | edit source]In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leaves that are to receive the substructures of the assigned value.
let 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']};
const arr = [];
({baz: [arr[0], arr[3]], foo: a, bar: b} = e);
console.log(`${a},${b},${arr}`); // displays: 5,6,Baz,,,Content
[a, b] = [b, a]; // swap contents of a and b
console.log(a + ',' + b); // displays: 6,5
[a, b, c] = [3, 4, 5]; // permutations
[a, b, c] = [b, c, a];
console.log(`${a},${b},${c}`); // displays: 4,5,3
Spread/rest operator
[edit | edit source]The ECMAScript 2015 standard introduced the "..." array operator, for the related concepts of "spread syntax"[16] and "rest parameters".[17] Object spreading was added in ECMAScript 2018.
Spread syntax provides another way to destructure arrays and objects. For arrays, it indicates that the elements 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, "..." transforms "[...foo]" into "[foo[0], foo[1], foo[2]]", and "this.bar(...foo);" into "this.bar(foo[0], foo[1], foo[2]);", and "{ ...bar }" into { prop: bar.prop, prop2: bar.prop2 }.
const a = [1, 2, 3, 4];
// It can be used multiple times in the same expression
const b = [...a, ...a]; // b = [1, 2, 3, 4, 1, 2, 3, 4];
// It can be combined with non-spread items.
const 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.
const 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}`);
}
// Users 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]);
// Users 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);
// For comparison, doing this without the spread operator
// 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 }
When ... 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 Array 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).
function foo(a, b, ...c) {
console.log(c.length);
}
foo(1, 2, 3, 4, 5); // "3" → c = [3, 4, 5]
foo('a', 'b'); // "0" → c = []
Rest parameters are similar to Javascript's arguments object, which is an array-like object that contains all of the parameters (named and unnamed) in the current function call. Unlike arguments, however, rest parameters are true Array objects, so methods such as .slice() and .sort() can be used on them directly.
Comparison
[edit | edit source]== | equal |
!= | not equal |
> | greater than |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
=== | identical (equal and of same type) |
!== | not identical |
Variables referencing objects are equal or identical only if they reference the same object:
const obj1 = {a: 1};
const obj2 = {a: 1};
const obj3 = obj1;
console.log(obj1 == obj2); //false
console.log(obj3 == obj1); //true
console.log(obj3 === obj1); //true
See also String.
Logical
[edit | edit source]JavaScript provides four logical operators:
- unary negation (
NOT = !a) - binary disjunction (
OR = a || b) and conjunction (AND = a && b) - ternary conditional (
c ? t : f)
In the context of a logical operation, any expression evaluates to true except the following:
- Strings:
"",'', - Numbers:
0,-0,NaN, - Special:
null,undefined, - Boolean:
false.
The Boolean function can be used to explicitly convert to a primitive of type Boolean:
// Only empty strings return false
console.log(Boolean("") === false);
console.log(Boolean("false") === true);
console.log(Boolean("0") === true);
// Only zero and NaN return false
console.log(Boolean(NaN) === false);
console.log(Boolean(0) === false);
console.log(Boolean(-0) === false); // equivalent to -1*0
console.log(Boolean(-2) === true);
// All objects return true
console.log(Boolean(this) === true);
console.log(Boolean({}) === true);
console.log(Boolean([]) === true);
// These types return false
console.log(Boolean(null) === false);
console.log(Boolean(undefined) === false); // equivalent to Boolean()
The NOT operator evaluates its operand as a Boolean and returns the negation. Using the operator twice in a row, as a double negative, explicitly converts an expression to a primitive of type Boolean:
console.log( !0 === Boolean(!0));
console.log(Boolean(!0) === !!1);
console.log(!!1 === Boolean(1));
console.log(!!0 === Boolean(0));
console.log(Boolean(0) === !1);
console.log(!1 === Boolean(!1));
console.log(!"" === Boolean(!""));
console.log(Boolean(!"") === !!"s");
console.log(!!"s" === Boolean("s"));
console.log(!!"" === Boolean(""));
console.log(Boolean("") === !"s");
console.log(!"s" === Boolean(!"s"));
The ternary operator can also be used for explicit conversion:
console.log([] == false); console.log([] ? true : false); // “truthy”, but the comparison uses [].toString()
console.log([0] == false); console.log([0]? true : false); // [0].toString() == "0"
console.log("0" == false); console.log("0"? true : false); // "0" → 0 ... (0 == 0) ... 0 ← false
console.log([1] == true); console.log([1]? true : false); // [1].toString() == "1"
console.log("1" == true); console.log("1"? true : false); // "1" → 1 ... (1 == 1) ... 1 ← true
console.log([2] != true); console.log([2]? true : false); // [2].toString() == "2"
console.log("2" != true); console.log("2"? true : false); // "2" → 2 ... (2 != 1) ... 1 ← true
Expressions that use features such as post–incrementation (i++) have an anticipated 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.
console.log(a || b); // When a is true, there is no reason to evaluate b.
console.log(a && b); // When a is false, there is no reason to evaluate b.
console.log(c ? t : f); // When c is true, there is no reason to evaluate f.
In early versions of JavaScript and JScript, the binary logical operators returned a Boolean value (like most C-derived programming languages). However, all contemporary implementations return one of their operands instead:
console.log(a || b); // if a is true, return a, otherwise return b
console.log(a && b); // if a is false, return a, otherwise return b
Programmers who are more familiar with the behavior in C might find this feature surprising, but it allows for a more concise expression of patterns like null coalescing:
const s = t || "(default)"; // assigns t, or the default value, if t is null, empty, etc.
Logical assignment
[edit | edit source]??= |
Nullish assignment |
||= |
Logical Or assignment |
&&= |
Logical And assignment |
Bitwise
[edit | edit source]JavaScript supports the following binary bitwise operators:
& | AND |
| | OR |
^ | XOR |
! | NOT |
<< | shift left (zero fill at right) |
>> | shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the left |
>>> | shift right (zero fill at left). For positive numbers,>> and >>> yield the same result. |
Examples:
const x = 11 & 6;
console.log(x); // 2
JavaScript supports the following unary bitwise operator:
~ | NOT (inverts the bits) |
Bitwise Assignment
[edit | edit source]JavaScript supports the following binary assignment operators:
&= | and |
|= | or |
^= | xor |
<<= | shift left (zero fill at right) |
>>= | shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the left |
>>>= | shift right (zero fill at left). For positive numbers,>>= and >>>= yield the same result. |
Examples:
let x=7;
console.log(x); // 7
x<<=3;
console.log(x); // 7->14->28->56
String
[edit | edit source]= | assignment |
+ | concatenation |
+= | concatenate and assign |
Examples:
let str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
const str2 = "2" + 2; // "22", not "4" or 4.
??
[edit | edit source]JavaScript's nearest operator is ??, the "nullish coalescing operator", which was added to the standard in ECMAScript's 11th edition.[18] In earlier versions, it could be used via a Babel plugin, and in TypeScript. It evaluates its left-hand operand and, if the result value is not "nullish" (null or undefined), takes that value as its result; otherwise, it evaluates the right-hand operand and takes the resulting value as its result.
In the following example, a will be assigned the value of b if the value of b is not null or undefined, otherwise it will be assigned 3.
const a = b ?? 3;
Before the nullish coalescing operator, programmers would use the logical OR operator (||). But where ?? looks specifically for null or undefined, the || operator looks for any falsy value: null, undefined, "", 0, NaN, and of course, false.
In the following example, a will be assigned the value of b if the value of b is truthy, otherwise it will be assigned 3.
const a = b || 3;
Control structures
[edit | edit source]Compound statements
[edit | edit source]A pair of curly brackets { } and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
If ... else
[edit | edit source]if (expr) {
//statements;
} else if (expr2) {
//statements;
} else {
//statements;
}
Conditional (ternary) operator
[edit | edit source]The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the if statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what if is to statements.
const result = condition ? expression : alternative;
is the same as:
if (condition) {
const result = expression;
} else {
const result = alternative;
}
Unlike the if statement, the conditional operator cannot omit its "else-branch".
Switch statement
[edit | edit source]The syntax of the JavaScript switch statement is as follows:
switch (expr) {
case SOMEVALUE:
// statements;
break;
case ANOTHERVALUE:
// statements specific to ANOTHERVALUE
// no break statement, falling through to the following case
case ORANOTHERONE:
// statements for when ANOTHERVALUE || ORANOTHERONE
break; //The buck stops here.
case YETANOTHER:
// statements;
break;
default:
// statements;
break;
}
break;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.
- Expressions can be used instead of values.
- The default case (optional) is executed when the expression does not match any other specified cases.
- Braces are required.
For loop
[edit | edit source]The syntax of the JavaScript for loop is as follows:
for (initial; condition; loop statement) {
/*
statements will be executed every time
the for{} loop cycles, while the
condition is satisfied
*/
}
or
for (initial; condition; loop statement(iteration)) // one statement
For ... in loop
[edit | edit source]The syntax of the JavaScript for ... in loop is as follows:
for (var property_name in some_object) {
// statements using some_object[property_name];
}
- 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
if (some_object.hasOwnProperty(property_name)) { ... }. Thus, adding a method to the array prototype withArray.prototype.newMethod = function() {...}may causefor ... inloops to loop over the method's name.
While loop
[edit | edit source]The syntax of the JavaScript while loop is as follows:
while (condition) {
statement1;
statement2;
statement3;
...
}
Do ... while loop
[edit | edit source]The syntax of the JavaScript do ... while loop is as follows:
do {
statement1;
statement2;
statement3;
...
} while (condition);
With
[edit | edit source]The with statement adds all of the given object's properties and methods into the following block's scope, letting them be referenced as if they were local variables.
with (document) {
const a = getElementById('a');
const b = getElementById('b');
const c = getElementById('c');
};
- Note the absence of document. before each getElementById() invocation.
The semantics are similar to the with statement of Pascal.
Because the availability of with statements hinders program performance and is believed to reduce code clarity (since any given variable could actually be a property from an enclosing with), this statement is not allowed in strict mode.
Labels
[edit | edit source]JavaScript supports nested labels in most implementations. Loops or blocks can be labeled for the break statement, and loops for continue. Although goto is a reserved word,[19] goto is not implemented in JavaScript.
loop1: for (let a = 0; a < 10; ++a) {
if (a === 4) break loop1; // Stops after the 4th attempt
console.log('a = ' + a);
loop2: for (let 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
console.log('b = ' + b);
} //end of loop2
console.log('finished');
} //end of loop1
block1: {
console.log('Hello'); // Displays 'Hello'
break block1;
console.log('World'); // Will never get here
}
goto block1; // Parse error.
Functions
[edit | edit source]A function is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If a user exits the function without a return statement, the value undefined is returned.
function gcd(number1, number2) {
if (isNaN(number1*number2)) throw TypeError("Non-Numeric arguments not allowed.");
number1 = Math.round(number1);
number2 = Math.round(number2);
let difference = number1 - number2;
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,
//'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
Functions are first-class citizens 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 undefined (that can be implicitly cast to false). Within the function, the arguments may also be accessed through the arguments object; this provides access to all arguments using indices (e.g. arguments[0], arguments[1], ... arguments[n]), including those beyond the number of named arguments. (While the arguments list has a .length property, it is not an instance of Array; it does not have methods such as .slice(), .sort(), etc.)
function add7(x, y) {
if (!y) {
y = 7;
}
console.log(x + y + arguments.length);
};
add7(3); // 11
add7(3, 4); // 9
Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed.
const obj1 = {a : 1};
const obj2 = {b : 2};
function foo(p) {
p = obj2; // Ignores actual parameter
p.b = arguments[1];
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
console.log(`${obj1.a} ${obj2.b}`); // writes 1 3
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore, they implement full closures by remembering the outer function's local variables even after the outer function has exited.
let t = "Top";
let bar, baz;
function foo() {
let f = "foo var";
bar = function() { console.log(f) };
baz = function(x) { f = x; };
}
foo();
baz("baz arg");
bar(); // "baz arg" (not "foo var") even though foo() has exited.
console.log(t); // Top
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.[20]
[1,2,3].map(function(x) { return x*2;); //returns [2,4,6]
[1,2,3].map((x) => { return x*2;}); //same result
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.[21]
With the exception of iOS devices from Apple, generators are not implemented for browsers on mobile devices.[22]
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
Async/await
[edit | edit source]The await operator in JavaScript (and TypeScript) can only be used from inside an async function or at the top level of a module. If the parameter is a promise, execution of the async function will resume when the promise is resolved (unless the promise is rejected, in which case an error will be thrown that can be handled with normal JavaScript exception handling). If the parameter is a thenable object, a new promise will be constructed with the native Promise constructor by calling the object's then() method and passing in a handler that calls the resolve callback. Otherwise, the parameter itself will be returned immediately.[23]
Many libraries provide promise objects that can also be used with await, as long as they match the specification for native JavaScript promises. However, promises from the jQuery library were not Promises/A+ compatible until jQuery 3.0.[24]
Below is an example (modified from this[25] article):
interface DBResponse {
id: string;
rev?: string;
ok?: boolean;
}
interface Document {
_id: string;
_rev?: string;
[key: string]: any;
}
interface Database {
post(doc: object): Promise<DBResponse>;
get(id: string): Promise<Document>;
}
declare const db: Database;
async function createNewDoc(): Promise<Document> {
const response: DBResponse = await db.post({});
const doc: Document = await db.get(response.id);
return doc;
}
async function main(): Promise<void> {
try {
const doc: Document = await createNewDoc();
console.log(doc);
} catch (err: Error) {
console.error("Error creating or fetching document:", err);
}
}
main();
Node.js version 8 includes a utility that enables using the standard library callback-based methods as promises.[26]
Objects
[edit | edit source]For convenience, types are normally subdivided into primitives and objects. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values ("slots" in prototype-based programming terminology). Objects may be thought of as associative arrays or hashes, and are often implemented using these data structures. However, objects have additional features, such as a prototype chain, which ordinary associative arrays do not have.
JavaScript has several kinds of built-in objects, namely Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. 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
[edit | edit source]Objects can be created using a constructor or an object literal. The constructor can use either a built-in Object function or a custom function. It is a convention that constructor functions are given a name that starts with a capital letter:
// Constructor
const anObject = new Object();
// Object literal
const objectA = {};
const objectA2 = {}; // A != A2, {}s create new objects as copies.
const objectB = {index1: 'value 1', index2: 'value 2'};
// Custom constructor (see below)
Object literals and array literals allow one to easily create flexible data structures:
const myStructure = {
name: {
first: "Mel",
last: "Smith"
},
age: 33,
hobbies: ["chess", "jogging"]
};
This is the basis for JSON, which is a simple notation that uses JavaScript-like syntax for data exchange.
Methods
[edit | edit source]A 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 this is just automatically set to the object instance to the left of the ".". (There are also call and apply methods that can set this explicitly—some packages such as jQuery do unusual things with 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 initializes an object. When used with the new keyword, as is the norm, 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.
function px() { return this.prefix + "X"; }
function Foo(yz) {
this.prefix = "a-";
if (yz > 0) {
this.pyz = function() { return this.prefix + "Y"; };
} else {
this.pyz = function() { return this.prefix + "Z"; };
}
this.m1 = px;
return this;
}
const foo1 = new Foo(1);
const foo2 = new Foo(0);
foo2.prefix = "b-";
console.log("foo1/2 " + foo1.pyz() + foo2.pyz());
// foo1/2 a-Y b-Z
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px()
const baz = {"prefix": "c-"};
baz.m4 = px; // No need for a constructor to make an object.
console.log("m1/m3/m4 " + foo1.m1() + foo1.m3() + baz.m4());
// m1/m3/m4 a-X a-X c-X
foo1.m2(); // Throws an exception, because foo1.m2 does not exist.
Constructors
[edit | edit source]Constructor functions simply assign values to slots of a newly created object. The values may be data or other functions.
Example: Manipulating an object:
function MyObject(attributeA, attributeB) {
this.attributeA = attributeA;
this.attributeB = attributeB;
}
MyObject.staticC = "blue"; // On MyObject Function, not object
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
object.attributeC = new Date(); // add a new property
delete object.attributeB; // remove a property of object
// note that unlike C++, delete does not invoke a "destructor",
// but rather removes a property of an object.
console.log(object.attributeB); // undefined
The constructor itself is referenced in the object's prototype's constructor slot. So,
function Foo() {}
// Use of 'new' sets prototype slots (for example,
// 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 initialized with
// {} instead of new Foo.
// Even though Foo is set to y's constructor slot,
// this is ignored by instanceof - only y's prototype's
// constructor slot is considered.
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 prototype property, as discussed in the "Inheritance" section below.)
Object deletion is rarely used as the scripting engine will garbage collect objects that are no longer being referenced.
Inheritance
[edit | edit source]JavaScript supports inheritance hierarchies through prototyping in the manner of Self.
In the following example, the Derived class inherits from the Base class. When d is created as Derived, the reference to the base instance of Base is copied to d.base.
Derive does not contain a value for aBaseFunction, so it is retrieved from aBaseFunction when aBaseFunction is accessed. This is made clear by changing the value of base.aBaseFunction, which is reflected in the value of d.aBaseFunction.
Some implementations allow the prototype to be accessed or set explicitly using the __proto__ slot as shown below.
function Base() {
this.anOverride = function() { console.log("Base::anOverride()"); };
this.aBaseFunction = function() { console.log("Base::aBaseFunction()"); };
}
function Derived() {
this.anOverride = function() { console.log("Derived::anOverride()"); };
}
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()
d.aBaseFunction(); // Base::aNEWBaseFunction()
console.log(d.aBaseFunction == Derived.prototype.aBaseFunction); // true
console.log(d.__proto__ == base); // true in Mozilla-based implementations and false in many others.
The following shows clearly how references to prototypes are copied on instance creation, but that changes to a prototype can affect all instances that refer to it.
function m1() { return "One"; }
function m2() { return "Two"; }
function m3() { return "Three"; }
function Base() {}
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
t.m = m1; // Does affect baz, and any other derived classes.
console.log("baz.m1 " + baz.m()); // baz.m1 One
In practice many variations of these themes are used, and it can be both powerful and confusing.
Exception handling
[edit | edit source]JavaScript includes a try ... catch ... finally exception handling statement to handle run-time errors.
The try ... catch ... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:
try {
// Statements in which exceptions might be thrown
} catch (errorValue) {
// Statements that execute in the event of an exception
} finally {
// Statements that execute afterward either way
}
Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. The catch block can throw(errorValue), if it does not want to handle a specific error.
In any case the statements in the finally block are always executed. Although memory is automatically garbage collected, this can be used to manually perform cleanup of resources (such as closing files or connections).
Either the catch or the finally clause may be omitted. The catch argument is required.
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java:
try {
statement;
} catch (e if e == "InvalidNameException") {
statement;
} catch (e if e == "InvalidIdException") {
statement;
} catch (e if e == "InvalidEmailException") {
statement;
} catch (e) {
statement;
} finally {
statement;
}
In a browser, the onerror event is more commonly used to trap exceptions.
onerror = function (errorValue, url, lineNr) {...; return true;};
Native functions and methods
[edit | edit source]eval (expression)
[edit | edit source]Evaluates the first parameter as an expression, which can include assignment statements. Variables local to functions can be referenced by the expression. However, eval represents a major security risk, as it allows a bad actor to execute arbitrary code, so its use is discouraged.[27]
> (function foo() {
... var x = 7;
... console.log("val " + eval("x + 2"));
... })();
val 9
undefined
TypeScript-specific features
[edit | edit source]TypeScript, a superset of JavaScript developed by Microsoft, adds the following syntax extensions to JavaScript:
- Type signatures (annotations) and compile-time type checking
- Type inference
- Interfaces
- Enumerated types
- Generics
- Namespaces
- Tuples
- Explicit resource management[28]
Syntactically, TypeScript is very similar to JScript .NET, another Microsoft implementation of the ECMA-262 language standard that added support for static typing and classical object-oriented language features such as classes, inheritance, interfaces, and namespaces. Other inspirations include Java and C#.
Type annotations
[edit | edit source]TypeScript provides static typing through type annotations to enable type checking at compile time.
function add(left: number, right: number): number {
return left + right;
}
Primitive types are annotated using all-lowercase types, such as number, boolean, bigint, and string. These types are distinct from their boxed counterparts (Number, Boolean, etc.), which cannot have operations performed from values directly (a Number and number cannot be added). Also are undefined and null types for their respective values.
All other non-primitive types are annotated using their class name, such as Error. Arrays can be written in two different ways which are both syntactically the same: the generic-based syntax Array<T> and a shorthand with T[].
Further built-in data types are tuples, unions, never, unknown, void, and any:
- An array with predefined data types at each index is a tuple, represented as
[type1, type2, ..., typeN]. - A variable that can hold more than one type of data is a union, represented using the logical OR
|symbol (string | number). - The
nevertype is used when a given type should be impossible to create, which is useful for filtering mapped types. - The
unknowntype is used when dealing with data of an unpredictable shape. Unlikeany, anunknown-typed variable will throw compilation errors when attempting to access properties or methods on that variable without first narrowing the type to something known. This type is often used for catching Errors, handling API responses, or user input.[29] - The
voidtype is used to represent the lack of a type, e.g. from a function with noreturnstatement. - A value of type
anysupports the same operations as a value in JavaScript and minimal static type checking is performed,[30] which makes it suitable for weakly or dynamically typed structures. This is generally discouraged practice and should be avoided when possible.[31]
Type annotations can be exported to a separate declarations file to make type information available for TypeScript scripts using types already compiled into JavaScript. Annotations can be declared for an existing JavaScript library, as has been done for Node.js and jQuery.
The TypeScript compiler makes use of type inference when types are not given. For example, the add method in the code above would be inferred as returning a number even if no return type annotation had been provided. This is based on the static types of left and right being numbers, and the compiler's knowledge that the result of adding two numbers is always a number.
If no type can be inferred because of lack of declarations (such as in a JavaScript module without types), then it defaults to the dynamic any type. Additional module types can be provided using a .d.ts declaration file using the declare module "moduleName" syntax.
Declaration files
[edit | edit source]When a TypeScript script gets compiled, there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process, the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.
The concept of declaration files is analogous to the concept of header files found in C/C++.
declare namespace Arithmetics {
add(left: number, right: number): number;
subtract(left: number, right: number): number;
multiply(left: number, right: number): number;
divide(left: number, right: number): number;
}
Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.
Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped.
Generics
[edit | edit source]TypeScript supports generic programming using a syntax similar to Java.[32] The following is an example of the identity function.[33]
function identity<T>(x: T): T {
return x;
}
Similar to Java generics, it is possible to bound a type parameter:
function f<T extends string>(x: T): void {
// ...
}
function prop<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Also, like C++, it is possible to have default generics parameters.
function makeArray<T = number>(value: T): T[] {
return [value];
}
Classes
[edit | edit source]TypeScript uses the same annotation style for class methods and fields as for functions and variables respectively. Compared with vanilla JavaScript classes, a TypeScript class can also implement an interface through the implements keyword, use generic parameters similarly to Java, and specify public and private fields.
class Person {
public name: string;
private age: number;
private salary: number;
constructor(name: string, age: number, salary: number) {
this.name = name;
this.age = age;
this.salary = salary;
}
toString(): string {
return `${this.name} (${this.age}) (${this.salary})`;
}
}
Union types
[edit | edit source]Union types are supported in TypeScript.[34] When TypeScript code is transpiled to JavaScript, all type-related information is lost.[35] This means that there is no one way to identify the type of a value at runtime as it appears in TypeScript. However, all JavaScript values are implicitly "tagged" with a type by the language, which may be retrieved using the typeof operator for primitive values and the instanceof operator for classes. Because JavaScript uses a dynamic type system, how operations such as addition or indexing will behave is determined at runtime based on the type of the value. This means if all members of a union type support a given operation, no additional work has to be done to perform said operation.
function length(v: string | any[]): number {
// Because both strings and arrays have a "length" property,
// we can use it without having to figure out the actual type of v.
return v.length;
}
function containsTheLetterA(v: string | string[] | number): boolean {
// sometimes, it is important to know the exact type of a value.
if (typeof v === "string") {
return v.includes("a");
} else if (v instanceof Array) {
// Because v is an Array, we want to check if any element includes the letter A.
return v.some((element) => element.includes("a"));
} else {
// Because we know it isn't an array or string, it must be a number.
// Numbers don't ever contain the letter a.
return false;
}
}
Enumerated types
[edit | edit source]TypeScript adds an enum data type to JavaScript.
enum CardSuit {
Clubs,
Diamonds,
Hearts,
Spades
};
let c: CardSuit = CardSuit.Diamonds;
By default, enums number members starting at 0; this can be overridden by setting the value of the first member:
enum CardSuit {
Clubs = 1,
Diamonds,
Hearts,
Spades
};
let c: CardSuit = CardSuit.Diamonds;
Each number may also be set:
enum CardSuit {
Clubs = 1,
Diamonds = 2,
Hearts = 4,
Spades = 8
};
let c: CardSuit = CardSuit.Diamonds;
TypeScript supports mapping the numeric value to its name. For example, this finds the name of the value 2:
enum CardSuit {
Clubs = 1,
Diamonds,
Hearts,
Spades
};
let suitName: string = CardSuit[2];
alert(suitName); // Diamonds
Modules and namespaces
[edit | edit source]TypeScript distinguishes between modules and namespaces, similar to C++ modules. Both features in TypeScript support encapsulation of classes, interfaces, functions and variables into containers. Namespaces (formerly internal modules) use JavaScript immediately-invoked function expressions to encapsulate code, whereas modules (formerly external modules) use existing JavaScript library patterns (CommonJS or ES Modules).[36]
Resource management
[edit | edit source]Although TypeScript does not have manual memory management, it has resource management similar to using-with-resource blocks in C# or try-with-resources blocks in Java, or C++ resource acquisition is initialization, that automatically close resources without need for finally blocks. In TypeScript, to automatically close an object, it must implement a global interface Disposable, and implement a method Symbol.dispose(). This will automatically be called at the end of scope.[28]
import * as fs from 'fs';
class TempFile implements Disposable {
#path: string;
#handle: number;
constructor(path: string) {
this.#path = path;
this.#handle = fs.openSync(path, "w+");
}
write(data: string): void {
fs.writeSync(this.#handle, data);
}
[Symbol.dispose](): void {
fs.closeSync(this.#handle);
fs.unlinkSync(this.#path);
}
}
export function doSomeWork() {
using file: TempFile = new TempFile(".some_temp_file.txt");
if (someCondition()) {
// do something here
}
}
See also
[edit | edit source]References
[edit | edit source]- ↑ "JavaScript 1.1 specification". Archived from the original on 26 February 2017. Retrieved 19 April 2006.
- ↑ "Chapter 1. Basic JavaScript". speakingjs.com. Archived from the original on 10 February 2022. Retrieved 22 September 2020.
- ↑ Flanagan, David (2006). JavaScript: The definitive Guide. O'Reilly Media, Inc. p. 16. ISBN 978-0-596-10199-2.
Omitting semicolons is not a good programming practice; you should get into the habit of inserting them.
- ↑ Farias, Bradley. "Hashbang Grammar". GitHub. Retrieved 13 July 2025.
- ↑ "Storing the information you need — Variables - Learn web development | MDN". developer.mozilla.org. 9 May 2023. Retrieved 23 June 2023.
- ↑ "Values, Variables, and Literals - MDC". Mozilla Developer Network. 16 September 2010. Archived from the original on 29 June 2011. Retrieved 1 February 2020.
- ↑ "JavaScript Hoisting". W3Schools. Archived from the original on 31 March 2022. Retrieved 17 December 2021.
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.
- ↑ "JavaScript Scoping and Hoisting Archived 8 May 2021 at the Wayback Machine", Ben Cherry Archived 28 February 2021 at the Wayback Machine, Adequately Good Archived 8 March 2022 at the Wayback Machine, 8 February 2010
- ↑ ECMA-262 5e edition clarified this behavior with the 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).
- ↑ "Number - JavaScript". MDN Web Docs. Retrieved 13 July 2025.
- 1 2 "BigInt - Javascript". MDN Web Docs. Retrieved 13 July 2025.
- ↑ "Template literals". MDN Web Docs. Archived from the original on 31 March 2022. Retrieved 4 November 2023.
- ↑ "Comparison Operators - MDC Doc Center". Mozilla. 5 August 2010. Archived from the original on 4 May 2012. Retrieved 5 March 2011.
- ↑ "The Elements of JavaScript Style". Douglas Crockford. Archived from the original on 17 March 2011. Retrieved 5 March 2011.
- ↑ Orendorff, Jason. "ES6 In Depth: Symbols". Mozilla Hacks. Retrieved 13 July 2025.
- ↑ "Spread syntax (...) - JavaScript | MDN". developer.mozilla.org. 25 September 2023.
- ↑ "rest parameters". 9 September 2024. Archived from the original on 30 May 2018. Retrieved 29 September 2016.
- ↑ "ECMAScript 2020 Language Specification". Ecma International. June 2020.
- ↑ ECMA-262, Edition 3, 7.5.3 Future Reserved Words
- ↑ Yadav, Amitya (4 October 2024). "Named function vs Anonymous Function Impacts". medium.com. Retrieved 19 February 2025.
- ↑ "function*". mdm web docs. Retrieved 23 February 2025.
- ↑ "ES6 Generators". medium.com. Retrieved 23 February 2025.
- ↑ "await - JavaScript (MDN)". Retrieved 13 August 2026.
- ↑ "jQuery Core 3.0 Upgrade Guide". Retrieved 2 May 2017.
- ↑ "Taming the asynchronous beast with ES7". Retrieved 12 November 2015.
- ↑ Foundation, Node.js (30 May 2017). "Node v8.0.0 (Current) - Node.js". Node.js.
- ↑ "eval()". MDN Web Docs. Archived from the original on 1 April 2022. Retrieved 29 January 2020.
- 1 2 "Documentation – TypeScript 5.2". www.typescriptlang.org. Archived from the original on 9 August 2024. Retrieved 9 November 2023.
- ↑ "Handbook - Basic Types". www.typescriptlang.org. Retrieved 2 July 2025.
- ↑ "TypeScript Language Specification p.24" (PDF). Archived from the original (PDF) on 17 November 2013.
- ↑ "TypeScript: Documentation – Everyday Types". www.typescriptlang.org. Archived from the original on 9 August 2024. Retrieved 30 March 2021.
- ↑ Turner, Jonathan (18 June 2013). "Announcing TypeScript 0.9". TypeScript Language team blog. Microsoft. Archived from the original on 26 November 2013. Retrieved 18 June 2013.
- ↑ "Generics in Typescript". Microsoft. Archived from the original on 5 April 2020. Retrieved 8 April 2020.
- ↑ "Handbook - Unions and Intersection Types". www.typescriptlang.org. Retrieved 30 November 2020.
- ↑ "TypeScript: Documentation - The Basics". www.typescriptlang.org. Retrieved 21 August 2026.
- ↑ Sothmann, Sönke (31 January 2014). "An introduction to TypeScript's module system". blog.oio.de. Archived from the original on 1 February 2014. Retrieved 21 February 2014.
Further reading
[edit | edit source]- Danny Goodman: JavaScript Bible, Wiley, John & Sons, ISBN 0-7645-3342-8.
- David Flanagan, Paula Ferguson: JavaScript: The Definitive Guide, O'Reilly & Associates, ISBN 0-596-10199-6.
- Thomas A. Powell, Fritz Schneider: JavaScript: The Complete Reference, McGraw-Hill Companies, ISBN 0-07-219127-9.
- Axel Rauschmayer: Speaking JavaScript: An In-Depth Guide for Programmers, 460 pages, O'Reilly Media, 25 February 2014, ISBN 978-1449365035. (free online edition)
- Emily Vander Veer: JavaScript For Dummies, 4th Edition, Wiley, ISBN 0-7645-7659-3.
External links
[edit | edit source]- A re-introduction to JavaScript - Mozilla Developer Center
- JavaScript Loops
- ECMAScript standard references: ECMA-262
- Interactive JavaScript Lessons - example-based
- JavaScript Training
- Mozilla Developer Center Core References for JavaScript versions 1.5, 1.4, 1.3 and 1.2
- Mozilla JavaScript Language Documentation