Content deleted Content added
remove eyesore sidebar that is redundant with the normal template at the bottom of the article |
m added code tags to improve consistency across article |
||
(110 intermediate revisions by 61 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 <code>console.log()</code> function
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, <
==Origins==
[[Brendan Eich]] summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification<ref>
{{Quote|JavaScript borrows most of its syntax from [[Java (programming language)|Java]], but also inherits from [[Awk]] and [[Perl]], with some indirect influence from [[Self (programming language)|Self]] in its object prototype system.}}
Line 18 ⟶ 19:
===Case sensitivity===
JavaScript is [[Case sensitivity|case sensitive]]. It is common to start the name of a [[
Example:
<syntaxhighlight lang="javascript">
var a = 5;
console.log(a); // 5
console.log(A); // throws a ReferenceError: A is not defined
Line 29 ⟶ 30:
===Whitespace and semicolons===
Unlike in [[C (programming language)|C]], whitespace in JavaScript source can directly impact [[Semantics (computer science)|semantics]]. [[Semicolon]]s end statements in JavaScript. Because of
|title=JavaScript: The definitive Guide
|url=https://archive.org/details/javascript00libg_297
Line 38 ⟶ 39:
|quote=Omitting semicolons is not a good programming practice; you should get into the habit of inserting them.
|isbn=978-0-596-10199-2
|year=2006
}}</ref>
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="javascript">
Line 53 ⟶ 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="javascript">
Line 65 ⟶ 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="javascript">
Line 79 ⟶ 81:
===Comments===
[[Comment (computer programming)|Comment]] syntax is the same as in [[C++]], [[Swift (programming language)|Swift]] and
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">
/
/* 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 <
===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.
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
Function declarations, which declare a variable and assign a function to it<!-- Function technically isn't actually a type. They're objects which can be executed in a subroutine. -->, are similar to variable statements, but in addition to hoisting the declaration, they also hoist the assignment – as if the entire statement appeared at the top of the containing function – and thus forward reference is also possible: the ___location of a function statement within an enclosing function is irrelevant. This is different from a function expression being assigned to a variable in a <code>var</code>, <code>let</code>, or <code>const</code> statement.
Line 114 ⟶ 121:
===Declaration and assignment===
Variables declared outside a scope are
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.
Line 132 ⟶ 139:
function f() {
var z = 'foxes', r = 'birds'; // 2 local variables
m = 'fish'; // global, because it
function child() {
Line 158 ⟶ 165:
<syntaxhighlight lang="javascript">
for (const i = 0; i < 10; i++) console.log(i); // throws a TypeError: Assignment to constant variable
for (const i of [1,2,3]) console.log(i); //will not raise an exception. i is not reassigned but recreated in every iteration
const pi; // throws a SyntaxError: Missing initializer in const declaration
Line 163 ⟶ 172:
==Primitive data types==
{{Main|Primitive data type}}
The JavaScript language provides six [[primitive data type]]s:
* Undefined
Line 175 ⟶ 185:
===Undefined===
{{Main|Undefined value}}
The [[undefined value|value of "undefined"]] is assigned to all [[uninitialized variable]]s, and is also returned when checking for object properties that do not exist. In a Boolean context, the undefined value is considered a false value.
Line 180 ⟶ 192:
<syntaxhighlight lang="javascript">
// ... set to value of undefined
console.log(test); // test variable exists, but value not ...
// ... defined, displays undefined
Line 193 ⟶ 205:
Note: There is no built-in language literal for undefined. Thus {{code|lang=javascript|code=(x === undefined)}} is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it is legal for someone to write {{code|lang=javascript|code=var undefined = "I'm defined now";}}. A more robust approach is to compare using {{code|lang=javascript|code=(typeof x === 'undefined')}}.
Functions like this
<syntaxhighlight lang="javascript">
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}} if {{mono|my_var}} is an unknown identifier, whereas {{code|lang=javascript|code=typeof my_var === 'undefined'}}
===Number===
Numbers are represented in binary as [[IEEE
This becomes an issue when comparing or formatting numbers. For example:
Line 227 ⟶ 239:
</syntaxhighlight>
There
<syntaxhighlight lang="javascript">
// Note: Wikipedia syntax
1_000_000_000; // Used with big numbers
1_000_000.5; // Support with decimals
Line 240 ⟶ 252:
0xFFFF_FFFF_FFFF_FFFE;
// But
_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 (
12._0; // Syntax error
12e_6; // Syntax error (next to "e", a non-digit.
1000____0000; // Syntax error (next to "_", a non-digit. Only 1 separator at a time is allowed
</syntaxhighlight>
Line 269 ⟶ 281:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Line 277 ⟶ 289:
<syntaxhighlight lang="javascript">
const myNumericWrapper = new Number(123.456);
</syntaxhighlight>
Line 289 ⟶ 301:
console.log(nan !== nan); // true
//
console.log(isNaN("converted to NaN")); // true
console.log(isNaN(NaN)); // true
Line 297 ⟶ 309:
===BigInt===
In JavaScript, regular numbers are represented with the IEEE 754 floating point type, meaning integers can only safely be stored if the value falls between <code>Number.MIN_SAFE_INTEGER</code> and <code>Number.MAX_SAFE_INTEGER</code>. <ref>{{cite web |title=Number - JavaScript | url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number |website=MDN Web Docs |access-date=13 July 2025}}</ref> BigInts instead represent [[integers]] of any size, allowing programmers to store integers too high or low to be represented with the IEEE 754 format.<ref name="bigint-mdn">{{cite web |title=BigInt - Javascript |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt |website=MDN Web Docs |access-date=13 July 2025}}</ref>
There are two ways to declare a BigInt value. An <code>n</code> can be appended to an integer, or the <code>BigInt</code> function can be used:<ref name="bigint-mdn" />
<syntaxhighlight lang="javascript">
const a = 12345n; // Creates a variable and stores a BigInt value of 12345
const b = BigInt(12345);
</syntaxhighlight>
=== String ===
A [[String (computer science)|string]] in JavaScript is a sequence of characters. In JavaScript, strings can be created directly (as literals) by placing the series of characters between double (<code>"</code>) or single (<code>'</code>) quotes. Such strings must be written on a single line, but may include escaped newline characters (such as <code>\n</code>). The JavaScript standard allows the [[Grave accent#Use in programming|backquote]] character (<code>`</code>, a.k.a. grave accent or backtick) to quote multiline literal strings,
<syntaxhighlight lang="javascript">
const aMultilineGreeting = `Warm regards,
John Doe.`
// Template literals type-coerce evaluated expressions and interpolate them into the string.
const templateLiteral = `This is what is stored in anotherGreeting: ${anotherGreeting}.`;
console.log(templateLiteral); // 'This is what is stored in anotherGreeting: 'Greetings, people of Earth.''
console.log(`You are ${Math.floor(age)=>18 ? "allowed" : "not allowed"} to view this web page`);
</syntaxhighlight>
Line 312 ⟶ 336:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Line 318 ⟶ 342:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Line 330 ⟶ 354:
<syntaxhighlight lang="javascript">
// ... false since the ...
// ... first characters ...
// ... of both operands ...
// ... are not of the same case.
</syntaxhighlight>
Line 342 ⟶ 366:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Line 350 ⟶ 374:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Line 356 ⟶ 380:
<syntaxhighlight lang="javascript">
typeof s; // Is 'object'.
typeof s.valueOf(); // Is 'string'.
Line 364 ⟶ 388:
<syntaxhighlight lang="javascript">
s1 == s2; // Is false, because they are two distinct objects.
s1.valueOf() == s2.valueOf(); // Is true.
Line 372 ⟶ 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 if it is {{mono|true}}, or to 0 if it is {{mono|false}}.
;{{small|Object}}: If an object is compared with a number or string, JavaScript attempts to return the default value for the object. An object is converted to a primitive String or Number value, using the {{mono|.valueOf()}} or {{mono|.toString()}} methods of the object. If this fails, a runtime error is generated.
==== Boolean type conversion ====
{{anchor|truthy and falsy}}
{{further|Truthy (computing)}}
[[Douglas Crockford]] advocates the terms "truthy" and "falsy" to describe how values of various types behave when evaluated in a logical context, especially in regard to edge cases.<ref>{{cite web | url=http://javascript.crockford.com/style2.html | title=The Elements of JavaScript Style | publisher=Douglas Crockford | access-date=5 March 2011 | archive-date=17 March 2011 | archive-url=https://web.archive.org/web/20110317074944/http://javascript.crockford.com/style2.html | url-status=live }}</ref>
The binary logical operators returned a Boolean value in early versions of JavaScript, but now they return one of the operands instead. The left–operand is returned, if it can be evaluated as : {{mono|false}}, in the case of [[logical conjunction|conjunction]]: (<code>a && b</code>), or {{mono|true}}, in the case of [[logical disjunction|disjunction]]: (<code>a || b</code>); otherwise the right–operand is returned. Automatic type coercion by the comparison operators may differ for cases of mixed Boolean and number-compatible operands (including strings that can be evaluated as a number, or objects that can be evaluated as such a string), because the Boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a Boolean primitive by doubling the logical [[negation|negation operator]]: ({{mono|!!}}), using the {{mono|Boolean()}} function, or using the [[Conditional (programming)|conditional operator]]: (<code>c ? t : f</code>).
Line 405 ⟶ 433:
console.log(true === !!2); // true.... data types and values match
console.log(true === !!0); // false... data types match, but values differ
console.log( 1 ? true : false); // true.... only ±0 and NaN are
console.log("0" ? true : false); // true.... only the empty string is
console.log(Boolean({})); // true.... all objects are
</syntaxhighlight>
Line 413 ⟶ 441:
<syntaxhighlight lang="javascript">
n = new Boolean(b.valueOf()); // Preferred
Line 427 ⟶ 455:
===Symbol===
Symbols are a feature introduced in [[ES6]]. Each symbol is guaranteed to be a unique value, and they can be used for [[Encapsulation (computer programming)|encapsulation]].<ref>{{cite web |last1=Orendorff |first1=Jason |title=ES6 In Depth: Symbols |url=https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/ |website=Mozilla Hacks |access-date=13 July 2025}}</ref>
Example:
<syntaxhighlight lang="javascript">
x === y; // => false
// since x and y are unique,
Line 464 ⟶ 492:
There are also ''well known symbols''. <!-- TODO: Add table or something -->
One of which is <code>Symbol.iterator</code>; if something implements <code>Symbol.iterator</code>, it
<syntaxhighlight lang="javascript">
x[Symbol.iterator] === Array.prototype[Symbol.iterator]; // and Arrays are iterable
Line 496 ⟶ 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="javascript">
// ... created, empty Array
myArray.push("hello World"); // Fill the next empty index, in this case 0
console.log(myArray[0]);
</syntaxhighlight>
Arrays have a <
Elements of <
<syntaxhighlight lang="javascript">
Line 516 ⟶ 545:
</syntaxhighlight>
The above two are equivalent. It
<syntaxhighlight lang="javascript">
Line 523 ⟶ 552:
</syntaxhighlight>
Declaration of an array can use either an <
<syntaxhighlight lang="javascript">
Line 530 ⟶ 559:
// Array literals
myArray = [1, 2]; // length of 2
myArray = [1, 2,]; // same array -
// It
myArray = [0, 1, /* hole */, /* hole */, 4, 5]; // length of 6
myArray = [0, 1, /* hole */, /* hole */, 4, 5,]; // same array
Line 542 ⟶ 571:
</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 <
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
<syntaxhighlight lang="javascript">
const dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
Line 555 ⟶ 584:
<syntaxhighlight lang="javascript">
const cats = [{color: "brown", size: "large"},
{color: "black", size: "small"}];
cats[0]["size"]; // results in "large"
const dogs = {rover: {color: "brown", size: "large"},
spot: {color: "black", size: "small"}};
dogs["spot"]["size"]; // results in "small"
Line 567 ⟶ 596:
===Date===
A <
<syntaxhighlight lang="javascript">
Line 576 ⟶ 605:
</syntaxhighlight>
Methods to extract fields are provided, as well as a useful <
<syntaxhighlight lang="javascript">
// Displays '2010-3-1 14:25:30':
Line 585 ⟶ 614:
+ d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds());
// Built-in toString returns something like 'Mon
console.log(d);
</syntaxhighlight>
Line 591 ⟶ 620:
===Error===
Custom error messages can be created using the <
<syntaxhighlight lang="javascript">
Line 600 ⟶ 629:
===Math===
The
{| class="wikitable" border="1"
Line 607 ⟶ 636:
!Property!!Returned value<br />rounded to 5 digits!!Description
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|}
Line 629 ⟶ 658:
!Example!!Returned value<br />rounded to 5 digits!!Description
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|}
Line 773 ⟶ 802:
====Capturing groups====
<syntaxhighlight lang="javascript">
if (results) {
console.log("Matched: " + results[0]); // Entire match
console.log(
} else console.log("Did not find a valid date!");
</syntaxhighlight>
===Function===
Every function in JavaScript is an instance of the <
<syntaxhighlight lang="javascript">
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
add(1, 2); // => 3
</syntaxhighlight>
Line 795 ⟶ 824:
<syntaxhighlight lang="javascript">
return x + y;
};
Line 801 ⟶ 830:
</syntaxhighlight>
In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain the <
<syntaxhighlight lang="javascript">
// values can also be implicitly returned (i.e. no return statement is needed)
add(1, 2); // => 3
Line 821 ⟶ 850:
</syntaxhighlight>
Hoisting allows
<syntaxhighlight lang="javascript">
Line 882 ⟶ 911:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Line 899 ⟶ 928:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
<syntaxhighlight lang="javascript">
console.log(++x); // x becomes 2; displays 2
console.log(x++); // displays 2; x becomes 3
Line 921 ⟶ 950:
<syntaxhighlight lang="javascript">
console.log(x%5); // displays 2
console.log(x%6); // displays 5
Line 929 ⟶ 958:
</syntaxhighlight>
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again:
<syntaxhighlight lang="javascript">
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 939 ⟶ 973:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Line 957 ⟶ 991:
<syntaxhighlight lang="javascript">
x += 1;
console.log(x); // displays: 10
Line 976 ⟶ 1,010:
* To learn JavaScript objects...
*/
object_3.a = 2;
Line 990 ⟶ 1,024:
message(); // displays 7 7 2
object_3.a = 5; // object_3
message(); // displays 7 7 5
Line 1,009 ⟶ 1,043:
<syntaxhighlight lang="javascript">
[a, b, c] = [3, 4, 5];
console.log(`${a
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
({baz: [arr[0], arr[3]], foo: a, bar: b}
console.log(`${a
[a, b] = [b, a]; // swap contents of a and b
console.log(a + ',' + b); // displays: 6,5
Line 1,021 ⟶ 1,055:
[a, b, c] = [3, 4, 5]; // permutations
[a, b, c] = [b, c, a];
console.log(`${a
</syntaxhighlight>
==== Spread/rest operator ====
The ECMAScript 2015 standard
'''Spread syntax''' provides another way to destructure arrays and objects.
In other words, "<
<syntaxhighlight lang="javascript" line="1">
// It can be used multiple times in the same expression
// It can be combined with non-spread items.
// For comparison, doing this without the spread operator
// creates a nested array.
// It works the same with function calls
function foo(arg1, arg2, arg3) {
console.log(`${arg1
}
//
foo(...a); // "1:2:3" → foo(a[0], a[1], a[2], a[3]);
//
foo(5, ...a, 6); // "5:1:2" → foo(5, a[0], a[1], a[2], a[3], 6);
Line 1,059 ⟶ 1,093:
// assigns the array to arg1, and nothing to the other parameters.
foo(a); // "1,2,3,4:undefined:undefined"
const bar = { a: 1, b: 2, c: 3 };
// This would copy the object
const copy = { ...bar }; // copy = { a: 1, b: 2, c: 3 };
// "b" would be overridden here
const override = { ...bar, b: 4 }; // override = { a: 1, c: 3, b: 4 }
</syntaxhighlight>
When <
<syntaxhighlight lang="javascript">
Line 1,072 ⟶ 1,114:
</syntaxhighlight>
Rest parameters are similar to Javascript's <
===Comparison===
{| class=wikitable
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Line 1,099 ⟶ 1,139:
<syntaxhighlight lang="javascript">
console.log(obj1 == obj2); //false
console.log(obj3 == obj1); //true
Line 1,111 ⟶ 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="javascript">
Line 1,174 ⟶ 1,214:
</syntaxhighlight>
Expressions that use features such as post–incrementation (<
<syntaxhighlight lang="javascript">
Line 1,192 ⟶ 1,232:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Line 1,198 ⟶ 1,238:
{| class="wikitable"
|-
| align="center" | <
| Nullish assignment
|-
| align="center" | <
| Logical Or assignment
|-
| align="center" | <
| Logical And assignment
|}
=== Bitwise ===
JavaScript supports the following '''binary [[Bitwise operation|bitwise operators]]''':
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <code>!</code> || NOT
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Line 1,233 ⟶ 1,271:
<syntaxhighlight lang="javascript">
const x = 11 & 6;
console.log(x); // 2
</syntaxhighlight>
Line 1,241 ⟶ 1,279:
{| class="wikitable"
|-
| align="center" | <
|}
Line 1,250 ⟶ 1,288:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Line 1,266 ⟶ 1,304:
<syntaxhighlight lang="javascript">
let x=7;
console.log(x); // 7
x<<=3;
Line 1,276 ⟶ 1,314:
{| class="wikitable"
|-
| align="center" | <
|-
| align="center" | <
|-
| align="center" | <
|}
Line 1,286 ⟶ 1,324:
<syntaxhighlight lang="javascript">
let str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
const str2 = "2" + 2; // "22", not "4" or 4.
</syntaxhighlight>
Line 1,299 ⟶ 1,337:
===Compound statements===
A pair of curly brackets <
===If ... else===
Line 1,317 ⟶ 1,355:
<syntaxhighlight lang="javascript">
</syntaxhighlight>
Line 1,323 ⟶ 1,361:
<syntaxhighlight lang="javascript">
const result = expression;
const result = alternative;
</syntaxhighlight>
Line 1,341 ⟶ 1,379:
break;
case ANOTHERVALUE:
// statements for when ANOTHERVALUE || ORNAOTHERONE
// no break statement, falling through to the following case
case ORANOTHERONE:
// statements specific to ORANOTHERONE (i.e. !ANOTHERVALUE && ORANOTHER);
break; //The buck stops here.
case YETANOTHER:
// statements;
break;
Line 1,349 ⟶ 1,393:
</syntaxhighlight>
* <
* Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
* String literal values can also be used for the case values.
Line 1,376 ⟶ 1,420:
===For ... in loop===
The syntax of the JavaScript <code>[[Foreach loop|for ... in loop]]</code> is as follows:
<syntaxhighlight lang="javascript">
Line 1,386 ⟶ 1,430:
* Iterates through all enumerable properties of an object.
* Iterates through all used indices of array including all user-defined properties of array object, if any. Thus it may be better to use a traditional for loop with a numeric index when iterating over arrays.
* There are differences between the various Web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice, each browser returns a slightly different set of properties during introspection. It is useful to test for a given property using {{nowrap|{{code|lang=javascript|code=if (some_object.hasOwnProperty(property_name)) { ... } }}}}. Thus, adding a method to the array prototype with {{nowrap|{{code|lang=javascript|code=Array.prototype.newMethod = function() {...} }}}} may cause <code>for ... in</code> loops to loop over the method's name.
===While loop===
Line 1,417 ⟶ 1,461:
<syntaxhighlight lang="javascript">
with (document) {
};
</syntaxhighlight>
Line 1,429 ⟶ 1,473:
===Labels===
JavaScript supports nested labels in most implementations. Loops or blocks can be
<syntaxhighlight lang="javascript">
loop1: for (
if (a === 4)
console.log('a = ' + a);
loop2: for (
if (b === 3)
if (b === 6) continue
console.log('b = ' + b);
} //end of loop2
console.log('finished');
} //end of loop1
block1: {
console.log('Hello'); // Displays 'Hello'
Line 1,457 ⟶ 1,495:
==Functions==
{{Main|Function (computer programming)}}
A [[
<syntaxhighlight lang="javascript+genshitext">
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);
}
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>
Line 1,475 ⟶ 1,518:
Functions are [[first class object]]s and may be assigned to other variables.
The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value {{mono|undefined}} (that can be implicitly cast to false). Within the function, the arguments may also be accessed through the {{mono|arguments}} object; this provides access to all arguments using indices (e.g. {{code|lang=javascript|code=arguments[0], arguments[1], ... arguments[n]}}), including those beyond the number of named arguments. (While the arguments list has a <
<syntaxhighlight lang="javascript">
Line 1,491 ⟶ 1,534:
<syntaxhighlight lang="javascript">
function foo(p) {
p = obj2; // Ignores actual parameter
Line 1,498 ⟶ 1,541:
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
console.log(`${obj1.a}
</syntaxhighlight>
Line 1,504 ⟶ 1,547:
<syntaxhighlight lang="javascript">
function foo() {
bar = function() { console.log(
baz = function(x) {
}
foo();
baz("
bar(); //
console.log(
</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===
Line 1,527 ⟶ 1,600:
<syntaxhighlight lang="javascript">
// Constructor
// Object literal
// Custom constructor (see below)
Line 1,540 ⟶ 1,613:
<syntaxhighlight lang="javascript">
name: {
first: "Mel",
Line 1,553 ⟶ 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.
Line 1,575 ⟶ 1,648:
}
foo2.prefix = "b-";
Line 1,583 ⟶ 1,656:
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.
Line 1,589 ⟶ 1,662:
// m1/m3/m4 a-X a-X c-X
foo1.m2(); // Throws an exception, because foo1.m2
</syntaxhighlight>
Line 1,607 ⟶ 1,680:
console.log(MyObject.staticC); // blue
const object = new MyObject('red', 1000);
console.log(object.attributeA); // red
console.log(object
console.log(object.staticC); // undefined
Line 1,618 ⟶ 1,691:
console.log(object.attributeB); // undefined
</syntaxhighlight>
Line 1,629 ⟶ 1,700:
// x = new Foo() would set x's prototype to Foo.prototype,
// and Foo.prototype has a constructor slot pointing back to Foo).
const x = new Foo();
// The above is almost equivalent to
const y = {};
y.constructor = Foo;
y.constructor();
// Except
x.constructor == y.constructor; // true
x instanceof Foo; // true
y instanceof Foo; // false
// y's prototype is Object.prototype, not
// Foo.prototype, since it was
// {} instead of new Foo.
// Even though Foo is set to y's constructor slot,
Line 1,646 ⟶ 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,671 ⟶ 1,742:
}
const base = new Base();
Derived.prototype = base; // Must be before new Derived()
Derived.prototype.constructor = Derived; // Required to make `instanceof` work
const d = new Derived(); // Copies Derived.prototype to d instance's hidden prototype slot.
d instanceof Derived; // true
d instanceof Base; // true
base.aBaseFunction = function() { console.log("Base::aNEWBaseFunction()"); };
d.anOverride(); // Derived::anOverride()
Line 1,698 ⟶ 1,769:
Base.prototype.m = m2;
const bar = new Base();
console.log("bar.m " + bar.m()); // bar.m Two
function Top() { this.m = m3; }
const t = new Top();
const foo = new Base();
Base.prototype = t;
// No effect on foo, the *reference* to t is copied.
console.log("foo.m " + foo.m()); // foo.m Two
const baz = new Base();
console.log("baz.m " + baz.m()); // baz.m Three
Line 1,757 ⟶ 1,828:
==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">{{
<syntaxhighlight lang="
> (function foo() {
... var x = 7;
... console.log("val " + eval("x + 2"));
... })();
val 9
undefined
</syntaxhighlight>
Line 1,788 ⟶ 1,859:
* ECMAScript standard references: [http://www.ecma-international.org/publications/standards/Ecma-262.htm ECMA-262]
* [https://web.archive.org/web/20120527095306/http://javalessons.com/cgi-bin/fun/java-tutorials-main.cgi?sub=javascript&code=script Interactive JavaScript Lessons - example-based]
* [http://javascript.about.com/ JavaScript on About.com: lessons and explanation] {{Webarchive|url=https://web.archive.org/web/20170225135310/http://javascript.about.com/ |date=25 February 2017 }}
* [https://web.archive.org/web/20150110202627/http://wisentechnologies.com/it-courses/JavaScript-Training-in-Chennai.aspx JavaScript Training]
* Mozilla Developer Center Core References for JavaScript versions [https://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference 1.5], [https://web.archive.org/web/20070210000908/http://research.nihonsoft.org/javascript/CoreReferenceJS14/index.html 1.4], [https://web.archive.org/web/20070210000504/http://research.nihonsoft.org/javascript/ClientReferenceJS13/index.html 1.3] and [https://web.archive.org/web/20070210000545/http://research.nihonsoft.org/javascript/jsref/index.htm 1.2]
Line 1,797 ⟶ 1,868:
{{DEFAULTSORT:Javascript Syntax}}
[[Category:JavaScript|syntax]]
[[Category:Articles with example JavaScript code]]
[[Category:Programming language syntax]]
|