Content deleted Content added
George8211 (talk | contribs) →Variables: update for ES6 |
m added code tags to improve consistency across article |
||
(297 intermediate revisions by more than 100 users not shown) | |||
Line 1:
{{Short description|Set of rules defining correctly structured programs}}
{{Update|date=November 2020|reason=New features/versions now in JavaScript}}
{{Use dmy dates|date=April 2022}}
{{Use American English|date=April 2025}}
[[File:Source code in Javascript.png|thumb|A snippet of [[JavaScript]] code with keywords [[Syntax highlighting|highlighted]] in different colors]]
The '''[[Syntax (programming languages)|syntax]] of [[JavaScript]]''' is the set of rules that define a correctly structured JavaScript program.
The examples below make use of the
The JavaScript [[standard library]] lacks an official standard text output function ==Origins==
[[Brendan Eich]] summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification<ref>
{{
==Basics==
===Case sensitivity===
JavaScript is [[Case sensitivity|case sensitive]]. It is common to start the name of a [[
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 [[
|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
}}</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 "<
<syntaxhighlight lang="
a = b + c
(d + e).foo()
Line 36 ⟶ 55:
with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use of ''leading'' semicolons on lines starting with '<
<syntaxhighlight lang="
a = b + c
;(d + e).foo()
Line 48 ⟶ 67:
Initial semicolons are also sometimes used at the start of JavaScript libraries, in case they are appended to another library that omits a trailing semicolon, as this can result in ambiguity of the initial statement.
The five restricted productions are <
<syntaxhighlight lang="
return
a + b;
Line 62 ⟶ 81:
===Comments===
[[Comment (computer programming)|Comment]] syntax is the same as in [[C++]],
Single-line comments begin with <code>//</code> and continue until the end of the line. A second type of comments can also be made; these start with <code>/*</code> and end with <code>*/</code> and can be used for multi-line comments.
A third type of comment, the hashbang comment, starts with <code>#!</code> and continues until the end of the line. They are only valid at the start of files and are intended for use in [[command-line interface|CLI]] environments.<ref>{{cite web |last1=Farias |first1=Bradley |title=Hashbang Grammar |url=https://github.com/tc39/proposal-hashbang |website=GitHub |access-date=13 July 2025}}</ref>
<syntaxhighlight lang="javascript">
#! 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 "A" through "Z" are different from the lowercase characters "a" through "z".
Starting with JavaScript 1.5, [[ISO 8859-1]] or [[Unicode]] letters (or <code>\uXXXX</code> Unicode escape sequences) can be used in identifiers.<ref>{{cite web | url=https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals&revision=22#Variables | title=Values, Variables, and Literals - MDC | date=16 September 2010 | publisher=Mozilla Developer Network | access-date=1 February 2020 | archive-url=https://web.archive.org/web/20110629131728/https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals%26revision%3D22#Variables | archive-date=29 June 2011 | url-status=dead }}</ref> In certain JavaScript implementations, the at sign (@) can be used in an identifier, but this is contrary to the specifications and not supported in newer implementations. {{Citation needed|date=January 2021}}
===Scoping and hoisting===
Variables declared with <code>var</code> are [[lexical scoping|lexically scoped]] at a [[function scope|function level]],
Function
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
===Declaration and assignment===
Variables declared outside
When JavaScript tries to '''resolve''' an identifier, it looks in the local
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"
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
<!-- Maybe in this example, function f should also have a local shadowing variable name x2 -->
<syntaxhighlight lang="
var
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
function child() {
Line 119 ⟶ 150:
child();
return
}
f();
</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:
* Undefined
* Number
* BigInt
* String
* Boolean
* Symbol
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="
// ... set to value of undefined
// ... defined, displays undefined
// ... displays undefined
</syntaxhighlight>
Note: There is no built-in language literal for undefined. Thus
Functions like this
<syntaxhighlight lang="
function isUndefined(x) {
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}}
===Number===
Numbers are represented in binary as [[IEEE
This becomes an issue when comparing or formatting numbers. For example:
<syntaxhighlight lang="
</syntaxhighlight>
Line 184 ⟶ 229:
Numbers may be specified in any of these notations:
<syntaxhighlight lang="
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
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 does not support numeric separators yet
1_000_000_000; // Used with big numbers
1_000_000.5; // Support with decimals
1_000e1_000; // Support with exponents
// Support with binary, octals and hex
0b0000_0000_0101_1011;
0o0001_3520_0237_1327;
0xFFFF_FFFF_FFFF_FFFE;
// But users cannot use them next to a non-digit number part, or at the start or end
_12; // Variable is not defined (the underscore makes it a variable identifier)
12_; // Syntax error (cannot be at the end of numbers)
12_.0; // Syntax error (does not make sense to put a separator next to the decimal point)
12._0; // Syntax error
12e_6; // Syntax error (next to "e", a non-digit. Does not make sense to put a separator at the start)
1000____0000; // Syntax error (next to "_", a non-digit. Only 1 separator at a time is allowed
</syntaxhighlight>
The extents [[extended real number line|'''+∞''', '''−∞''']] and '''[[NaN]]''' (Not a Number) of the number type may be obtained by two program expressions:
<syntaxhighlight lang="
Infinity; // positive infinity (negative obtained with -Infinity for instance)
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="
</syntaxhighlight>
When used as a constructor, a numeric ''wrapper'' object is created (though it is of little use):
<syntaxhighlight lang="
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
// Users can use the isNaN methods 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);
</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
<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(`You are ${Math.floor(age)=>18 ? "allowed" : "not allowed"} to view this web page`);
</syntaxhighlight>
<syntaxhighlight lang="
</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="
</syntaxhighlight>
However, JavaScript strings are [[immutable object|immutable]]:
<syntaxhighlight lang="
greeting[0] = "H"; // Fails.
</syntaxhighlight>
Applying the <!-- loose -->equality operator ("==") to two strings returns true, if the strings have the same contents, which means: of the same length and containing the same sequence of characters (case is significant for alphabets). Thus:
<syntaxhighlight lang="
// ... false since the ...
// ... first characters ...
// ... of both operands ...
// ... are not of the same case.
</syntaxhighlight>
<syntaxhighlight lang="
</syntaxhighlight>
The {{mono|String}} constructor creates a string object (an object wrapping a string):
<syntaxhighlight lang="
</syntaxhighlight>
These objects have a {{mono|valueOf}} method returning the primitive string wrapped within them<!-- also works with regular strings -->:
<syntaxhighlight lang="
typeof s; // Is 'object'.
typeof s.valueOf(); // Is 'string'.
Line 279 ⟶ 387:
Equality between two {{mono|String}} objects does not behave as with string primitives:
<syntaxhighlight lang="
s1 == s2; // Is false, because they are two distinct objects.
s1.valueOf() == s2.valueOf(); // Is true.
Line 288 ⟶ 396:
===Boolean===
[[JavaScript]] provides a [[Boolean data type]] with {{mono|true}} and {{mono|false}} literals. The {{mono|[[typeof]]}} operator returns the string {{mono|"boolean"}} for these [[primitive types]]. When used in a logical context, {{mono|0}}, {{mono|-0}}, {{mono|null}}, {{mono|NaN}}, {{mono|undefined}}, and the empty string ({{mono|""}}) evaluate as {{mono|false}} due to automatic [[type
=== 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
;{{small|Object}}: If an object is compared with a number or string, JavaScript attempts to return the default value for the object. An object is converted to a primitive String or Number value, using the {{mono|.valueOf()}} or {{mono|.toString()}} methods of the object. If this fails, a runtime error is generated.
==== Boolean type conversion ====
{{anchor|truthy and falsy}}
{{further|Truthy (computing)}}
[[Douglas Crockford]] advocates the terms "truthy" and "falsy" to describe how values of various types behave when evaluated in a logical context, especially in regard to edge cases.<ref>{{cite web | url=http://javascript.crockford.com/style2.html | title=The Elements of JavaScript Style | publisher=Douglas Crockford | access-date=5 March 2011 | archive-date=17 March 2011 | archive-url=https://web.archive.org/web/20110317074944/http://javascript.crockford.com/style2.html | url-status=live }}</ref>
The binary logical operators returned a Boolean value in early versions of JavaScript, but now they return one of the operands instead. The left–operand is returned, if it can be evaluated as : {{mono|false}}, in the case of [[logical conjunction|conjunction]]: (<code>a && b</code>), or {{mono|true}}, in the case of [[logical disjunction|disjunction]]: (<code>a || b</code>); otherwise the right–operand is returned. Automatic type coercion by the comparison operators may differ for cases of mixed Boolean and number-compatible operands (including strings that can be evaluated as a number, or objects that can be evaluated as such a string), because the Boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a Boolean primitive by doubling the logical [[negation|negation operator]]: ({{mono|!!}}), using the {{mono|Boolean()}} function, or using the [[Conditional (programming)|conditional operator]]: (<code>c ? t : f</code>).
<syntaxhighlight lang="javascript">
// Automatic type coercion
console.log(true == 2 ); // false... true → 1 !== 2 ← 2
console.log(NaN == NaN); // false...... NaN is not equivalent to anything, including NaN.
// Type checked comparison (no conversion of types and values)
// Explicit type coercion
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 {}
n = new Boolean(b.valueOf()); // Preferred
if (0 || -0 || "" || null || undefined || b.valueOf() || !new Boolean() || !t) {
} else if ([] && {} && b && typeof b === "object" && b.toString() === "false") {
}
</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==
Line 346 ⟶ 524:
===Array===
{{Main|Array data type}}
An [[Array data type|Array]] is a JavaScript object prototyped from the <code>Array</code> constructor specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (for example, <code>join</code>, <code>slice</code>, and <code>push</code>).
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 <
<syntaxhighlight lang="
// ... created, empty Array
myArray.push("hello World"); // Fill the next empty index, in this case 0
</syntaxhighlight>
Arrays have a <
Elements of <
<syntaxhighlight lang="
myArray[1]; // the 2nd item in myArray
myArray["1"];
</syntaxhighlight>
The above two are equivalent. It
<syntaxhighlight lang="
myArray.1; // syntax error
myArray["01"]; // not the same as myArray[1]
</syntaxhighlight>
Declaration of an array can use either an <
<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 =
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 {{
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
<syntaxhighlight lang="
const dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
Line 394 ⟶ 583:
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="
const cats = [{color: "brown", size: "large"},
{color: "black", size: "small"}];
cats[0]["size"]; // results in "large"
const dogs = {rover: {color: "brown", size: "large"},
spot:
dogs["spot"]["size"]; // results in "small"
dogs.rover.color; // results in "brown"
Line 407 ⟶ 596:
===Date===
A <
<syntaxhighlight lang="
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
Line 416 ⟶ 605:
</syntaxhighlight>
Methods to extract fields are provided, as well as a useful <
<syntaxhighlight lang="
// Displays '2010-3-1 14:25:30':
+ d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds());
// Built-in toString returns something like 'Mon
</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
{| class="wikitable" border="1"
|+
|-
!Property!!Returned value<br />rounded to 5 digits!!Description
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|}
Line 478 ⟶ 658:
!Example!!Returned value<br />rounded to 5 digits!!Description
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|}
===Regular expression===
{{main|Regular expression}}
<syntaxhighlight lang="
/expression/.test(string); // returns Boolean
"string".search(/expression/); // returns position Number
Line 523 ⟶ 703:
// Here are some examples
if (/Tom/.test("My name is Tom"))
</syntaxhighlight>
====Character classes====
<syntaxhighlight lang="
// \d - digit
// \D - non digit
Line 540 ⟶ 720:
// - - range
if (/\d/.test('0'))
if (/[0-9]/.test('6'))
if (/[13579]/.test('1'))
if (/\S\S\s\S\S\S\S/.test('My name'))
if (/\w\w\w/.test('Tom'))
if (/[a-zA-Z]/.test('B'))
</syntaxhighlight>
====Character matching====
<syntaxhighlight lang="
// A...Z a...z 0...9 - alphanumeric
// \u0000...\uFFFF - Unicode hexadecimal
Line 559 ⟶ 739:
// | - OR
if (/T.m/.test('Tom'))
if (/A|B/.test("A"))
</syntaxhighlight>
====Repeaters====
<syntaxhighlight lang="
// ? - 0 or 1 match
// * - 0 or more
Line 573 ⟶ 753:
// {n,m} - range n to m
if (/ab?c/.test("ac"))
if (/ab*c/.test("ac"))
if (/ab+c/.test("abc"))
if (/ab{3}c/.test("abbbc"))
if (/ab{3,}c/.test("abbbc"))
if (/ab{1,3}c/.test("abc"))
</syntaxhighlight>
====Anchors====
<syntaxhighlight lang="
// ^ - string starts with
// $ - string ends with
if (/^My/.test("My name is Tom"))
if (/Tom$/.test("My name is Tom"))
</syntaxhighlight>
====Subexpression====
<syntaxhighlight lang="
// ( ) - groups characters
if (/water(mark)?/.test("watermark"))
if (/(Tom)|(John)/.test("John"))
</syntaxhighlight>
====Flags====
<syntaxhighlight lang="
// /g - global
// /i - ignore upper/lower case
// /m - allow matches to span multiple lines
</syntaxhighlight>
====Advanced methods====
<syntaxhighlight lang="
my_array = my_string.split(my_delimiter);
// example
Line 621 ⟶ 801:
====Capturing groups====
<syntaxhighlight lang="
if (results) {
} else
</syntaxhighlight>
===Function===
Every function in JavaScript is an instance of the <
<syntaxhighlight lang="
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
</syntaxhighlight>
The add function above may also be defined using a function expression:
<syntaxhighlight lang="
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;
}
</syntaxhighlight>
<syntaxhighlight lang="
add(1, 2); // => 3, not a ReferenceError
function add(x, y) {
return x + y;
}
</syntaxhighlight>
A function instance has properties and methods.
<syntaxhighlight lang="
function subtract(x, y) {
return x - y;
}
/*
Line 682 ⟶ 879:
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="
// Concatenate 2 strings
// Add two numbers
// Adding a number and a string results in concatenation (from left to right)
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
</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>
Line 704 ⟶ 911:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <code>**</code> || exponentiation
|}
Line 719 ⟶ 928:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
<syntaxhighlight lang="
</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>
Line 741 ⟶ 973:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <code>+=</code> || add and assign
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
[[Assignment (computer science)|Assignment]] of [[primitive type]]s
<syntaxhighlight lang="
x += 1;
x *= 30;
x /= 6;
x -= 3;
x %= 7;
</syntaxhighlight>
Assignment of object types
<syntaxhighlight lang="
/**
* To learn JavaScript objects...
*/
object_3.a = 2;
message();
object_2 = object_1; // object_2 now references the same object as object_1
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
*/
function message() {
}
</syntaxhighlight>
Line 801 ⟶ 1,042:
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="
[a, b, c] = [3, 4, 5];
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
({baz: [arr[0], arr[3]], foo: a, bar: b}
[a, b] = [b, a]; // swap contents of a and b
[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" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Variables referencing objects are equal or identical only if they reference the same object:
<syntaxhighlight lang="
console.log(obj3 === obj1); //true
</syntaxhighlight>
Line 847 ⟶ 1,151:
===Logical===
JavaScript provides four logical operators:
* unary [[negation]] (<
* binary [[logical disjunction|disjunction]] (<
* ternary [[Conditional (programming)|conditional]] (<
In the context of a logical operation, any expression evaluates to true except the following''':'''
* Strings: <
* Numbers: <
* Special: <
* Boolean: <
The Boolean function can be used to explicitly convert to a primitive of type <
<syntaxhighlight lang="
// Only empty strings return false
// Only zero and NaN return false
// All objects return true
// These types return false
</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="
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="
</syntaxhighlight>
Expressions that use features such as post–incrementation
<syntaxhighlight lang="
</syntaxhighlight>
In early versions of JavaScript and [[JScript]], the binary logical operators returned a Boolean value (like most
<syntaxhighlight lang="
</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="
</syntaxhighlight>
===
{| 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" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| 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''':
Line 946 ⟶ 1,279:
{| class="wikitable"
|-
| align="center" | <
|}
===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===
Line 953 ⟶ 1,314:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Examples:
<syntaxhighlight lang="
let str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
const str2 = "2" + 2; // "22", not "4" or 4.
</syntaxhighlight>
===??===
{{excerpt|Null coalescing operator|JavaScript}}
==Control structures==
Line 973 ⟶ 1,337:
===Compound statements===
A pair of curly brackets <
===If ... else===
<syntaxhighlight lang="
if (expr) {
//statements;
Line 986 ⟶ 1,350:
</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="
</syntaxhighlight>
is the same as:
<syntaxhighlight lang="
const result = expression;
const result = alternative;
</syntaxhighlight>
Line 1,009 ⟶ 1,373:
The syntax of the JavaScript [[Control flow#Choice|switch statement]] is as follows:
<syntaxhighlight lang="
switch (expr) {
case SOMEVALUE:
// statements;
break;
case ANOTHERVALUE:
// statements
// no break statement, falling through to the following case
case ORANOTHERONE:
// statements specific to ORANOTHERONE (i.e. !ANOTHERVALUE && ORANOTHER);
break; //The buck stops here.
case YETANOTHER:
// statements;
break;
default:
// statements;
break;
}
</syntaxhighlight>
* <
* Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
*
* 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.
Line 1,033 ⟶ 1,403:
The syntax of the JavaScript [[for loop]] is as follows:
<syntaxhighlight lang="
for (initial; condition; loop statement) {
/*
Line 1,045 ⟶ 1,415:
or
<syntaxhighlight lang="
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="
for (var property_name in some_object) {
// statements using some_object[property_name];
}
</syntaxhighlight>
Line 1,060 ⟶ 1,430:
* Iterates through all enumerable properties of an object.
* Iterates through all used indices of array including all user-defined properties of array object, if any. Thus it may be better to use a traditional for loop with a numeric index when iterating over arrays.
* There are differences between the various Web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice, each browser returns a slightly different set of properties during introspection. It is useful to test for a given property using {{nowrap|{{code|lang=javascript|code=if (some_object.hasOwnProperty(property_name)) { ... }
===While loop===
The syntax of the JavaScript [[while loop]] is as follows:
<syntaxhighlight lang="
while (condition) {
statement1;
Line 1,077 ⟶ 1,447:
The syntax of the JavaScript <code>[[do while loop|do ... while loop]]</code> is as follows:
<syntaxhighlight lang="
do {
statement1;
Line 1,089 ⟶ 1,459:
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="
with (document) {
};
</syntaxhighlight>
Line 1,103 ⟶ 1,473:
===Labels===
JavaScript supports nested labels in most implementations. Loops or blocks can be
<syntaxhighlight lang="
loop1: for (
if (a === 4)
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
} //end of loop2
console.log('finished');
} //end of loop1
block1: {
break block1;
}
goto block1; // Parse error.
Line 1,131 ⟶ 1,495:
==Functions==
{{Main|Function (computer programming)}}
A [[
<syntaxhighlight lang="
function gcd(
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);
}
//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 object]]s and may be assigned to other variables.
The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value {{mono|undefined}} (that can be implicitly cast to false). Within the function, the arguments may also be accessed through the {{mono|arguments}} object; this provides access to all arguments using indices (e.g. {{code|lang=javascript|code=arguments[0], arguments[1], ... arguments[n]}}), including those beyond the number of named arguments. (While the arguments list has a <
<syntaxhighlight lang="
function add7(x, y) {
if (!y) {
y = 7;
}
};
add7(3); // 11
Line 1,164 ⟶ 1,533:
Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed.
<syntaxhighlight lang="
function foo(p) {
p = obj2; // Ignores actual parameter
Line 1,172 ⟶ 1,541:
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
</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="
function foo() {
bar = function() {
baz = function(x) {
}
foo();
baz("
bar(); //
</syntaxhighlight>
An ''anonymous function'' is simply a function without a name and can be written either using function or arrow notation. In these equivalent examples an anonymous function is passed to the '''map''' function and is applied to each of the elements of the array.<ref>{{cite web |last=Yadav |first=Amitya |date=4 October 2024 |title=Named function vs Anonymous Function Impacts |url=https://aditya003-ay.medium.com/named-function-vs-anonymous-function-impacts-94e2472ed7bb |website=medium.com |access-date=19 February 2025}}</ref>
<syntaxhighlight lang="javascript">
[1,2,3].map(function(x) { return x*2;); //returns [2,4,6]
[1,2,3].map((x) => { return x*2;}); //same result
</syntaxhighlight>
A ''generator function'' is signified placing an * after the keyword ''function'' and contains one or more ''yield'' statements. The effect is to return a value and pause execution at the current state. Declaring an generator function returns an iterator. Subsequent calls to ''iterator.next()'' resumes execution until the next ''yield''. When the iterator returns without using a yield statement there are no more values and the '''done''' property of the iterator is set to '''true'''.<ref> {{cite web |author=<!-- not stated --> |title=function* |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*|website=mdm web docs |access-date=23 February 2025}}</ref>
With the exception of [[iOS]] devices from Apple, generators are not implemented for browsers on mobile devices. <ref> {{cite web |author=<!-- not stated --> |title=ES6 Generators |url=https://caniuse.com/?search=generator|website=medium.com |access-date=23 February 2025}}</ref>
<syntaxhighlight lang="javascript">
function* generator() {
yield "red";
yield "green";
yield "blue";
}
let iterator=generator();
let current;
while(current=iterator.next().value)
console.log(current); //displays red, green then blue
console.log(iterator.next().done) //displays true
</syntaxhighlight>
===Async/await===
{{excerpt|Async/await|In JavaScript}}
==Objects==
For convenience, types are normally subdivided into ''primitives'' and ''objects''. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values ("slots" in [[prototype-based programming]] terminology). Objects may be thought of as [[associative arrays]] or hashes, and are often implemented using these data structures. However, objects have additional features, such as a
JavaScript has several kinds of built-in objects, namely <
===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="
// Constructor
// Object literal
// Custom constructor (see below)
Line 1,213 ⟶ 1,612:
Object literals and array literals allow one to easily create flexible data structures:
<syntaxhighlight lang="
name: {
first: "Mel",
last: "Smith"
},
age: 33,
Line 1,227 ⟶ 1,626:
===Methods===
A [[
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
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="
function px() { return this.prefix + "X"; }
Line 1,246 ⟶ 1,645:
}
this.m1 = px;
return this;
}
foo2.prefix = "b-";
// foo1/2 a-Y b-Z
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px()
baz.m4 = px; // No need for a constructor to make an object.
// m1/m3/m4 a-X a-X c-X
foo1.m2(); // Throws an exception, because foo1.m2
</syntaxhighlight>
Line 1,271 ⟶ 1,671:
Example: Manipulating an object:
<syntaxhighlight lang="
function MyObject(attributeA, attributeB) {
this.attributeA = attributeA;
Line 1,278 ⟶ 1,678:
MyObject.staticC = "blue"; // On MyObject Function, not object
const object = new MyObject('red', 1000);
object.attributeC = new Date(); // add a new property
delete object.attributeB; // remove a property of object
</syntaxhighlight>
The constructor itself is referenced in the object's prototype's ''constructor'' slot. So,
<syntaxhighlight lang="
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
// {} instead of new Foo.
// Even though Foo is set to y's constructor slot,
Line 1,319 ⟶ 1,717:
</syntaxhighlight>
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a special <
Object deletion is rarely used as the scripting engine will [[Garbage collection (computer science)|garbage collect]] objects that are no longer being referenced.
Line 1,333 ⟶ 1,731:
Some implementations allow the prototype to be accessed or set explicitly using the {{mono|__proto__}} slot as shown below.
<syntaxhighlight lang="
function Base() {
this.anOverride = function() {
this.aBaseFunction = function() {
}
function Derived() {
this.anOverride = function() {
}
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() {
d.anOverride(); // Derived::anOverride()
d.aBaseFunction(); // Base::aNEWBaseFunction()
</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="
function m1() { return "One"; }
function m2() { return "Two"; }
Line 1,371 ⟶ 1,769:
Base.prototype.m = m2;
const bar = new Base();
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.
const baz = new Base();
t.m = m1; // Does affect baz, and any other derived classes.
</syntaxhighlight>
Line 1,396 ⟶ 1,794:
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="
try {
// Statements in which exceptions might be thrown
Line 1,414 ⟶ 1,812:
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="
try { statement; }
catch (e if e == "InvalidNameException") { statement; }
Line 1,425 ⟶ 1,823:
<!-- This needs verification -->
<syntaxhighlight lang="
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"));
... })();
undefined
</syntaxhighlight>
Line 1,447 ⟶ 1,844:
==References==
{{Reflist}}
==Further reading==
* Danny Goodman: ''JavaScript Bible'', Wiley, John & Sons, {{ISBN
* David Flanagan, Paula Ferguson: ''JavaScript: The Definitive Guide'', O'Reilly & Associates, {{ISBN
* Thomas A. Powell, Fritz Schneider: ''JavaScript: The Complete Reference'', McGraw-Hill Companies, {{ISBN
* Axel Rauschmayer: ''Speaking JavaScript: An In-Depth Guide for Programmers'', 460 pages, O'Reilly Media, 25 February
* Emily Vander Veer: ''JavaScript For Dummies, 4th Edition'', Wiley, {{ISBN
==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]
* [http://javascript.about.com/ JavaScript on About.com: lessons and explanation] {{Webarchive|url=https://web.archive.org/web/20170225135310/http://javascript.about.com/ |date=25 February 2017 }}
* [https://web.archive.org/web/20150110202627/http://wisentechnologies.com/it-courses/JavaScript-Training-in-Chennai.aspx JavaScript Training]
* Mozilla Developer Center Core References for JavaScript versions [https://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference 1.5], [https://web.archive.org/web/20070210000908/http://research.nihonsoft.org/javascript/CoreReferenceJS14/index.html 1.4], [https://web.archive.org/web/20070210000504/http://research.nihonsoft.org/javascript/ClientReferenceJS13/index.html 1.3] and [https://web.archive.org/web/20070210000545/http://research.nihonsoft.org/javascript/jsref/index.htm 1.2]
* [https://developer.mozilla.org/en/docs/JavaScript Mozilla JavaScript Language Documentation]
{{JavaScript}}
{{DEFAULTSORT:Javascript Syntax}}
[[Category:JavaScript|syntax]]
[[Category:Articles with example JavaScript code]]
[[Category:Programming language syntax]]
|