![]() | This article needs to beupdated. The reason given is: New features/versions now in JavaScript. Please help update this article to reflect recent events or newly available information.(November 2020) |
Thesyntax ofJavaScript is the set of rules that define a correctly structured JavaScript program.
The examples below make use of theconsole.log()
function present in most browsers forstandard text output.
The JavaScriptstandard library lacks an official standard text output function (with the exception ofdocument.write
). Given that JavaScript is mainly used forclient-side scripting within modernweb browsers, and that almost all Web browsers provide the alert function,alert
can also be used, but is not commonly used.
Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification[1][2] as follows:
JavaScript borrows most of its syntax fromJava, but also inherits fromAwk andPerl, with some indirect influence fromSelf in its object prototype system.
JavaScript iscase sensitive. It is common to start the name of aconstructor with acapitalized letter, and the name of a function or variable with a lower-case letter.
Example:
vara=5;console.log(a);// 5console.log(A);// throws a ReferenceError: A is not defined
Unlike inC, whitespace in JavaScript source can directly impactsemantics.Semicolons end statements in JavaScript. Because ofautomatic semicolon insertion (ASI), some statements that are well formed when a newline isparsed will be considered complete, as if a semicolon were inserted just prior to the newline. Some authorities advise supplying statement-terminating semicolons explicitly, because it may lessen unintended effects of the automatic semicolon insertion.[3]
There are two issues: five tokens can either begin a statement or be the extension of a complete statement; and five restricted productions, where line breaks are not allowed in certain positions, potentially yielding incorrect parsing.
The five problematic tokens are the open parenthesis "(
", open bracket "[
", slash "/
", plus "+
", and minus "-
". Of these, the open parenthesis is common in theimmediately invoked function expression pattern, and open bracket occurs sometimes, while others are quite rare. An example:
a=b+c(d+e).foo()// Treated as:// a = b + c(d + e).foo();
with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use ofleading semicolons on lines starting with '(
' or '[
', so the line is not accidentally joined with the previous one. This is known as adefensive semicolon, and is particularly recommended, because code may otherwise become ambiguous when it is rearranged. For example:
a=b+c;(d+e).foo()// Treated as:// a = b + c;// (d + e).foo();
Initial semicolons are also sometimes used at the start of JavaScript libraries, in case they are appended to another library that omits a trailing semicolon, as this can result in ambiguity of the initial statement.
The five restricted productions arereturn
,throw
,break
,continue
, and post-increment/decrement. In all cases, inserting semicolons does not fix the problem, but makes the parsed syntax clear, making the error easier to detect.return
andthrow
take an optional value, whilebreak
andcontinue
take an optional label. In all cases, the advice is to keep the value or label on the same line as the statement. This most often shows up in the return statement, where one might return a large object literal, which might be accidentally placed starting on a new line. For post-increment/decrement, there is potential ambiguity with pre-increment/decrement, and again it is recommended to simply keep these on the same line.
returna+b;// Returns undefined. Treated as:// return;// a + b;// Should be written as:// return a + b;
Comment syntax is the same as inC++,Swift and other programming languages.
Single-line comments begin with//
and continue until the end of the line. A second type of comments can also be made; these start with/*
and end with*/
and can be used for multi-line comments.
A third type of comment, the hashbang comment, starts with#!
and continues until the end of the line. They are only valid at the start of files and are intended for use inCLI environments.[4]
#!Hashbangcomment// One-line comment/* Multi-line comment */
Variables in standard JavaScript have notype attached, so any value (eachvalue has a type) can be stored in any variable. Starting withES6, the 6th version of the language, variables could be declared withvar
for function scoped variables, andlet
orconst
which are forblock level variables. Before ES6, variables could only be declared with avar
statement. Values assigned to variables declared withconst
cannot be changed, but their properties can.var
should no longer be used sincelet
andconst
are supported by modern browsers.[5] A variable'sidentifier must start with a letter, underscore (_
), or dollar sign ($
), while subsequent characters can also be digits (0-9
). JavaScript is case sensitive, so the uppercase characters "A" through "Z" are different from the lowercase characters "a" through "z".
Starting with JavaScript 1.5,ISO 8859-1 orUnicode letters (or\uXXXX
Unicode escape sequences) can be used in identifiers.[6] In certain JavaScript implementations, the at sign (@) can be used in an identifier, but this is contrary to the specifications and not supported in newer implementations.[citation needed]
Variables declared withvar
arelexically scoped at afunction level, while ones withlet
orconst
have ablock level scope. Since declarations are processed before any code is executed, a variable can be assigned to and used prior to being declared in the code.[7] This is referred to ashoisting, and it is equivalent to variables beingforward declared at the top of the function or block.[8]
Withvar
,let
, andconst
statements, only the declaration is hoisted; assignments are not hoisted. Thus avarx=1
statement in the middle of the function is equivalent to avarx
declaration statement at the top of the function, and anx=1
assignment statement at that point in the middle of the function. This means that values cannot be accessed before they are declared;forward reference is not possible. Withvar
a variable's value isundefined
until it is initialized. Variables declared withlet
orconst
cannot be accessed until they have been initialized, so referencing such variables before will cause an error.
Function declarations, which declare a variable and assign a function to it, are similar to variable statements, but in addition to hoisting the declaration, they also hoist the assignment – as if the entire statement appeared at the top of the containing function – and thus forward reference is also possible: the location of a function statement within an enclosing function is irrelevant. This is different from a function expression being assigned to a variable in avar
,let
, orconst
statement.
So, for example,
varfunc=function(){..}// declaration is hoisted onlyfunctionfunc(){..}// declaration and assignment are hoisted
Block scoping can be produced by wrapping the entire block in a function and then executing it – this is known as theimmediately-invoked function expression pattern – or by declaring the variable using thelet
keyword.
Variables declared outside a scope areglobal. If a variable is declared in a higher scope, it can be accessed by child scopes.
When JavaScript tries toresolve 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 thescope chain until it reaches theglobal scope where global variables reside. If it is still not found, JavaScript will raise aReferenceError
exception.
Whenassigning an identifier, JavaScript goes through exactly the same process to retrieve this identifier, except that if it is not found in theglobal scope, it will create the "variable" in the scope where it was created.[9] As a consequence, a variable never declared will be global, if assigned. Declaring a variable (with the keywordvar
) in theglobal scope (i.e. outside of any function body (or block in the case of let/const)), assigning a never declared identifier or adding a property to theglobal object (usuallywindow) will also create a new global variable.
Note that JavaScript'sstrict mode forbids the assignment of an undeclared variable, which avoids global namespace pollution.
Here are some examples of variable declarations and scope:
varx1=0;// A global variable, because it is not in any functionletx2=0;// Also global, this time because it is not in any blockfunctionf(){varz='foxes',r='birds';// 2 local variablesm='fish';// global, because it was not declared anywhere beforefunctionchild(){varr='monkeys';// This variable is local and does not affect the "birds" r of the parent function.z='penguins';// Closure: Child function is able to access the variables of the parent function.}twenty=20;// This variable is declared on the next line, but usable anywhere in the function, even before, as herevartwenty;child();returnx1+x2;// We can use x1 and x2 here, because they are global}f();console.log(z);// This line will raise a ReferenceError exception, because the value of z is no longer available
for(leti=0;i<10;i++)console.log(i);console.log(i);// throws a ReferenceError: i is not defined
for(consti=0;i<10;i++)console.log(i);// throws a TypeError: Assignment to constant variablefor(constiof[1,2,3])console.log(i);//will not raise an exception. i is not reassigned but recreated in every iterationconstpi;// throws a SyntaxError: Missing initializer in const declaration
The JavaScript language provides sixprimitive data types:
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.
Thevalue of "undefined" is assigned to alluninitialized variables, and is also returned when checking for object properties that do not exist. In a Boolean context, the undefined value is considered a false value.
Note: undefined is considered a genuine primitive type. Unless explicitly converted, the undefined value may behave unexpectedly in comparison to other types that evaluate to false in a logical context.
lettest;// variable declared, but not defined, ...// ... set to value of undefinedconsttestObj={};console.log(test);// test variable exists, but value not ...// ... defined, displays undefinedconsole.log(testObj.myProp);// testObj exists, property does not, ...// ... displays undefinedconsole.log(undefined==null);// unenforced type during check, displays trueconsole.log(undefined===null);// enforce type during check, displays false
Note: There is no built-in language literal for undefined. Thus(x===undefined)
is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it is legal for someone to writevarundefined="I'm defined now";
. A more robust approach is to compare using(typeofx==='undefined')
.
Functions like this will not work as expected:
functionisUndefined(x){letu;returnx===u;}// like this...functionisUndefined(x){returnx===void0;}// ... or that second onefunctionisUndefined(x){return(typeofx)==="undefined";}// ... or that third one
Here, callingisUndefined(my_var)
raises aReferenceError ifmy_var is an unknown identifier, whereastypeofmy_var==='undefined'
does not.
Numbers are represented in binary asIEEE 754floating point doubles. Although this format provides an accuracy of nearly 16significant digits, it cannot always exactly represent real numbers, including fractions.
This becomes an issue when comparing or formatting numbers. For example:
console.log(0.2+0.1===0.3);// displays falseconsole.log(0.94-0.01);// displays 0.9299999999999999
As a result, a routine such as thetoFixed() method should be used to round numbers whenever they areformatted for output.
Numbers may be specified in any of these notations:
345;// an "integer", although there is only one numeric type in JavaScript34.5;// a floating-point number3.45e2;// another floating-point, equivalent to 3450b1011;// a binary integer equal to 110o377;// an octal integer equal to 2550xFF;// a hexadecimal integer equal to 255, digits represented by the ...// ... letters A-F may be upper or lowercase
There is also a numeric separator,_ (the underscore), introduced in ES2021:
// Note: Wikipedia syntax does not support numeric separators yet1_000_000_000;// Used with big numbers1_000_000.5;// Support with decimals1_000e1_000;// Support with exponents// Support with binary, octals and hex0b0000_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 error12e_6;// Syntax error (next to "e", a non-digit. Does not make sense to put a separator at the start)1000____0000;// Syntax error (next to "_", a non-digit. Only 1 separator at a time is allowed
The extents+∞,−∞ andNaN (Not a Number) of the number type may be obtained by two program expressions:
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
Infinity and NaN are numbers:
typeofInfinity;// returns "number"typeofNaN;// returns "number"
These three special values correspond and behave as theIEEE-754 describes them.
The Number constructor (used as a function), or a unary + or -, may be used to perform explicit numeric conversion:
constmyString="123.456";constmyNumber1=Number(myString);constmyNumber2=+myString;
When used as a constructor, a numericwrapper object is created (though it is of little use):
constmyNumericWrapper=newNumber(123.456);
However, NaN is not equal to itself:
constnan=NaN;console.log(NaN==NaN);// falseconsole.log(NaN===NaN);// falseconsole.log(NaN!==NaN);// trueconsole.log(nan!==nan);// true// Users can use the isNaN methods to check for NaNconsole.log(isNaN("converted to NaN"));// trueconsole.log(isNaN(NaN));// trueconsole.log(Number.isNaN("not converted"));// falseconsole.log(Number.isNaN(NaN));// true
In JavaScript, regular numbers are represented with the IEEE 754 floating point type, meaning integers can only safely be stored if the value falls betweenNumber.MIN_SAFE_INTEGER
andNumber.MAX_SAFE_INTEGER
.[10] BigInts instead representintegers of any size, allowing programmers to store integers too high or low to be represented with the IEEE 754 format.[11]
There are two ways to declare a BigInt value. Ann
can be appended to an integer, or theBigInt
function can be used:[11]
consta=12345n;// Creates a variable and stores a BigInt value of 12345constb=BigInt(12345);
Astring in JavaScript is a sequence of characters. In JavaScript, strings can be created directly (as literals) by placing the series of characters between double ("
) or single ('
) quotes. Such strings must be written on a single line, but may include escaped newline characters (such as\n
). The JavaScript standard allows thebackquote character (`
, a.k.a. grave accent or backtick) to quote multiline literal strings, as well as embedded expressions using the syntax${expression}
.[12]
constgreeting="Hello, World!";constanotherGreeting='Greetings, people of Earth.';constaMultilineGreeting=`Warm regards,John Doe.`// Template literals type-coerce evaluated expressions and interpolate them into the string.consttemplateLiteral=`This is what is stored in anotherGreeting:${anotherGreeting}.`;console.log(templateLiteral);// 'This is what is stored in anotherGreeting: 'Greetings, people of Earth.''console.log(`You are${Math.floor(age)=>18?"allowed":"not allowed"} to view this web page`);
Individual characters within a string can be accessed using thecharAt method (provided byString.prototype). This is the preferred way when accessing individual characters within a string, because it also works in non-modern browsers:
consth=greeting.charAt(0);
In modern browsers, individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays:
consth=greeting[0];
However, JavaScript strings areimmutable:
greeting[0]="H";// Fails.
Applying the equality operator ("==") to two strings returns true, if the strings have the same contents, which means: of the same length and containing the same sequence of characters (case is significant for alphabets). Thus:
constx="World";constcompare1=("Hello, "+x=="Hello, World");// Here compare1 contains true.constcompare2=("Hello, "+x=="hello, World");// Here compare2 contains ...// ... false since the ...// ... first characters ...// ... of both operands ...// ... are not of the same case.
Quotes of the same type cannot be nested unless they areescaped.
letx='"Hello, World!" he said.';// Just fine.x=""Hello,World!" he said.";// Not good.x="\"Hello, World!\" he said.";// Works by escaping " with \"
TheString constructor creates a string object (an object wrapping a string):
constgreeting=newString("Hello, World!");
These objects have avalueOf method returning the primitive string wrapped within them:
consts=newString("Hello !");typeofs;// Is 'object'.typeofs.valueOf();// Is 'string'.
Equality between twoString objects does not behave as with string primitives:
consts1=newString("Hello !");consts2=newString("Hello !");s1==s2;// Is false, because they are two distinct objects.s1.valueOf()==s2.valueOf();// Is true.
JavaScript provides aBoolean data type withtrue andfalse literals. Thetypeof operator returns the string"boolean" for theseprimitive types. When used in a logical context,0,-0,null,NaN,undefined, and the empty string ("") evaluate asfalse due to automatictype conversion. All other values (thecomplement of the previous list) evaluate astrue, including the strings"0","false" and any object.
Automatic type coercion by the equality comparison operators (==
and!=
) can be avoided by using the type checked comparison operators (===
and!==
).
When type conversion is required, JavaScript convertsBoolean,Number,String, orObject operands as follows:[13]
Douglas Crockford advocates the terms "truthy" and "falsy" to describe how values of various types behave when evaluated in a logical context, especially in regard to edge cases.[14]The binary logical operators returned a Boolean value in early versions of JavaScript, but now they return one of the operands instead. The left–operand is returned, if it can be evaluated as :false, in the case ofconjunction: (a && b
), ortrue, in the case ofdisjunction: (a || b
); otherwise the right–operand is returned. Automatic type coercion by the comparison operators may differ for cases of mixed Boolean and number-compatible operands (including strings that can be evaluated as a number, or objects that can be evaluated as such a string), because the Boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a Boolean primitive by doubling the logicalnegation operator: (!!), using theBoolean() function, or using theconditional operator: (c ? t : f
).
// Automatic type coercionconsole.log(true==2);// false... true → 1 !== 2 ← 2console.log(false==2);// false... false → 0 !== 2 ← 2console.log(true==1);// true.... true → 1 === 1 ← 1console.log(false==0);// true.... false → 0 === 0 ← 0console.log(true=="2");// false... true → 1 !== 2 ← "2"console.log(false=="2");// false... false → 0 !== 2 ← "2"console.log(true=="1");// true.... true → 1 === 1 ← "1"console.log(false=="0");// true.... false → 0 === 0 ← "0"console.log(false=="");// true.... false → 0 === 0 ← ""console.log(false==NaN);// false... false → 0 !== NaNconsole.log(NaN==NaN);// false...... NaN is not equivalent to anything, including NaN.// Type checked comparison (no conversion of types and values)console.log(true===1);// false...... data types do not match// Explicit type coercionconsole.log(true===!!2);// true.... data types and values matchconsole.log(true===!!0);// false... data types match, but values differconsole.log(1?true:false);// true.... only ±0 and NaN are "falsy" numbersconsole.log("0"?true:false);// true.... only the empty string is "falsy"console.log(Boolean({}));// true.... all objects are "truthy"
The new operator can be used to create an object wrapper for a Boolean primitive. However, thetypeof operator does not returnboolean for the object wrapper, it returnsobject. Because all objects evaluate astrue, a method such as.valueOf(), or.toString(), must be used to retrieve the wrapped value. For explicit coercion to the Boolean type, Mozilla recommends that theBoolean() function (withoutnew) be used in preference to the Boolean object.
constb=newBoolean(false);// Object false {}constt=Boolean(b);// Boolean trueconstf=Boolean(b.valueOf());// Boolean falseletn=newBoolean(b);// Not recommendedn=newBoolean(b.valueOf());// Preferredif(0||-0||""||null||undefined||b.valueOf()||!newBoolean()||!t){console.log("Never this");}elseif([]&&{}&&b&&typeofb==="object"&&b.toString()==="false"){console.log("Always this");}
Symbols are a feature introduced inES6. Each symbol is guaranteed to be a unique value, and they can be used forencapsulation.[15]
Example:
letx=Symbol(1);consty=Symbol(1);x===y;// => falseconstsymbolObject={};constnormalObject={};// since x and y are unique,// they can be used as unique keys in an objectsymbolObject[x]=1;symbolObject[y]=2;symbolObject[x];// => 1symbolObject[y];// => 2// as compared to normal numeric keysnormalObject[1]=1;normalObject[1]=2;// overrides the value of 1normalObject[1];// => 2// changing the value of x does not change the key stored in the objectx=Symbol(3);symbolObject[x];// => undefined// changing x back just creates another unique Symbolx=Symbol(1);symbolObject[x];// => undefined
There are alsowell known symbols.
One of which isSymbol.iterator
; if something implementsSymbol.iterator
, it is iterable:
constx=[1,2,3,4];// x is an Arrayx[Symbol.iterator]===Array.prototype[Symbol.iterator];// and Arrays are iterableconstxIterator=x[Symbol.iterator]();// The [Symbol.iterator] function should provide an iterator for xxIterator.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 valuesfor(constvalueofx){console.log(value);// 1 2 3 4}// Sets are also iterable:[Symbol.iterator]inSet.prototype;// truefor(constvalueofnewSet(['apple','orange'])){console.log(value);// "apple" "orange"}
The JavaScript language provides a handful of nativeobjects. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available.
AnArray is a JavaScript object prototyped from theArray
constructor specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (for example,join
,slice
, andpush
).
As in theC family, arrays use a zero-based indexing scheme: A value that is inserted into an empty array by means of thepush
method occupies the 0th index of the array.
constmyArray=[];// Point the variable myArray to a newly ...// ... created, empty ArraymyArray.push("hello World");// Fill the next empty index, in this case 0console.log(myArray[0]);// Equivalent to console.log("hello World");
Arrays have alength
property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated, if one creates a property with an even larger index. Writing a smaller number to thelength
property will remove larger indices.
Elements ofArray
s may be accessed using normal object property access notation:
myArray[1];// the 2nd item in myArraymyArray["1"];
The above two are equivalent. It is not possible to use the "dot"-notation or strings with alternative representations of the number:
myArray.1;// syntax errormyArray["01"];// not the same as myArray[1]
Declaration of an array can use either anArray
literal or theArray
constructor:
letmyArray;// Array literalsmyArray=[1,2];// length of 2myArray=[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 arraymyArray=[0,1,/* hole */,/* hole */,4,5];// length of 6myArray=[0,1,/* hole */,/* hole */,4,5,];// same arraymyArray=[0,1,/* hole */,/* hole */,4,5,/* hole */,];// length of 7// With the constructormyArray=newArray(0,1,2,3,4,5);// length of 6myArray=newArray(365);// an empty array with length 365
Arrays are implemented so that only the defined elements use memory; they are "sparse arrays". SettingmyArray[10]='someThing'
andmyArray[57]='somethingOther'
only uses space for these two elements, just like any other object. Thelength
of the array will still be reported as 58. The maximum length of an array is 4,294,967,295 which corresponds to 32-bit binary number (11111111111111111111111111111111)2.
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
constdog={color:"brown",size:"large"};dog["color"];// results in "brown"dog.color;// also results in "brown"
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both. (Technically, JavaScript does not support multidimensional arrays, but one can mimic them with arrays-of-arrays.)
constcats=[{color:"brown",size:"large"},{color:"black",size:"small"}];cats[0]["size"];// results in "large"constdogs={rover:{color:"brown",size:"large"},spot:{color:"black",size:"small"}};dogs["spot"]["size"];// results in "small"dogs.rover.color;// results in "brown"
ADate
object stores a signed millisecond count with zero representing 1970-01-01 00:00:00 UT and a range of ±108 days. There are several ways of providing arguments to theDate
constructor. Note that months are zero-based.
newDate();// create a new Date instance representing the current time/date.newDate(2010,2,1);// create a new Date instance representing 2010-Mar-01 00:00:00newDate(2010,2,1,14,25,30);// create a new Date instance representing 2010-Mar-01 14:25:30newDate("2010-3-1 14:25:30");// create a new Date instance from a String.
Methods to extract fields are provided, as well as a usefultoString
:
constd=newDate(2010,2,1,14,25,30);// 2010-Mar-01 14:25:30;// Displays '2010-3-1 14:25:30':console.log(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());// Built-in toString returns something like 'Mon 1 March, 2010 14:25:30 GMT-0500 (EST)':console.log(d);
Custom error messages can be created using theError
class:
thrownewError("Something went wrong.");
These can be caught by try...catch...finally blocks as described in the section onexception handling.
TheMath object contains various math-related constants (for example,π) and functions (for example, cosine). (Note that theMath object has no constructor, unlikeArray orDate. All its methods are "static", that is "class" methods.) All the trigonometric functions use angles expressed inradians, notdegrees orgrads.
Property | Returned value rounded to 5 digits | Description |
---|---|---|
Math.E | 2.7183 | e: Natural logarithm base |
Math.LN2 | 0.69315 | Natural logarithm of 2 |
Math.LN10 | 2.3026 | Natural logarithm of 10 |
Math.LOG2E | 1.4427 | Logarithm to the base 2 ofe |
Math.LOG10E | 0.43429 | Logarithm to the base 10 ofe |
Math.PI | 3.14159 | π: circumference/diameter of a circle |
Math.SQRT1_2 | 0.70711 | Square root of ½ |
Math.SQRT2 | 1.4142 | Square root of 2 |
Example | Returned value rounded to 5 digits | Description |
---|---|---|
Math.abs(-2.3) | 2.3 | Absolute value |
Math.acos(Math.SQRT1_2) | 0.78540 rad = 45° | Arccosine |
Math.asin(Math.SQRT1_2) | 0.78540 rad = 45° | Arcsine |
Math.atan(1) | 0.78540 rad = 45° | Half circlearctangent ( to) |
Math.atan2(-3.7, -3.7) | −2.3562 rad =−135° | Whole circle arctangent ( to) |
Math.ceil(1.1) | 2 | Ceiling:round up to smallest integer ≥ argument |
Math.cos(Math.PI/4) | 0.70711 | Cosine |
Math.exp(1) | 2.7183 | Exponential function:e raised to this power |
Math.floor(1.9) | 1 | Floor: round down to largest integer ≤ argument |
Math.log(Math.E) | 1 | Natural logarithm, basee |
Math.max(1, -2) | 1 | Maximum:(x > y) ? x : y |
Math.min(1, -2) | −2 | Minimum:(x < y) ? x : y |
Math.pow(-3, 2) | 9 | Exponentiation (raised to the power of):Math.pow(x, y) gives xy |
Math.random() | e.g. 0.17068 | Pseudorandom number between 0 (inclusive) and 1 (exclusive) |
Math.round(1.5) | 2 | Round to the nearest integer; half fractions are rounded up (e.g. 1.5 rounds to 2) |
Math.sin(Math.PI/4) | 0.70711 | Sine |
Math.sqrt(49) | 7 | Square root |
Math.tan(Math.PI/4) | 1 | Tangent |
/expression/.test(string);// returns Boolean"string".search(/expression/);// returns position Number"string".replace(/expression/,replacement);// Here are some examplesif(/Tom/.test("My name is Tom"))console.log("Hello Tom!");console.log("My name is Tom".search(/Tom/));// == 11 (letters before Tom)console.log("My name is Tom".replace(/Tom/,"John"));// == "My name is John"
// \d - digit// \D - non digit// \s - space// \S - non space// \w - word char// \W - non word// [ ] - one of// [^] - one not of// - - rangeif(/\d/.test('0'))console.log('Digit');if(/[0-9]/.test('6'))console.log('Digit');if(/[13579]/.test('1'))console.log('Odd number');if(/\S\S\s\S\S\S\S/.test('My name'))console.log('Format OK');if(/\w\w\w/.test('Tom'))console.log('Hello Tom');if(/[a-zA-Z]/.test('B'))console.log('Letter');
// A...Z a...z 0...9 - alphanumeric// \u0000...\uFFFF - Unicode hexadecimal// \x00...\xFF - ASCII hexadecimal// \t - tab// \n - new line// \r - CR// . - any character// | - ORif(/T.m/.test('Tom'))console.log('Hi Tom, Tam or Tim');if(/A|B/.test("A"))console.log('A or B');
// ? - 0 or 1 match// * - 0 or more// + - 1 or more// {n} - exactly n// {n,} - n or more// {0,n} - n or less// {n,m} - range n to mif(/ab?c/.test("ac"))console.log("OK");// match: "ac", "abc"if(/ab*c/.test("ac"))console.log("OK");// match: "ac", "abc", "abbc", "abbbc" etc.if(/ab+c/.test("abc"))console.log("OK");// match: "abc", "abbc", "abbbc" etc.if(/ab{3}c/.test("abbbc"))console.log("OK");// match: "abbbc"if(/ab{3,}c/.test("abbbc"))console.log("OK");// match: "abbbc", "abbbbc", "abbbbbc" etc.if(/ab{1,3}c/.test("abc"))console.log("OK");// match: "abc", "abbc", "abbbc"
// ^ - string starts with// $ - string ends withif(/^My/.test("My name is Tom"))console.log("Hi!");if(/Tom$/.test("My name is Tom"))console.log("Hi Tom!");
// ( ) - groups charactersif(/water(mark)?/.test("watermark"))console.log("Here is water!");// match: "water", "watermark",if(/(Tom)|(John)/.test("John"))console.log("Hi Tom or John!");
// /g - global// /i - ignore upper/lower case// /m - allow matches to span multiple linesconsole.log("hi tom!".replace(/Tom/i,"John"));// == "hi John!"console.log("ratatam".replace(/ta/,"tu"));// == "ratutam"console.log("ratatam".replace(/ta/g,"tu"));// == "ratutum"
my_array=my_string.split(my_delimiter);// examplemy_array="dog,cat,cow".split(",");// my_array==["dog","cat","cow"];my_array=my_string.match(my_expression);// examplemy_array="We start at 11:30, 12:15 and 16:45".match(/\d\d:\d\d/g);// my_array==["11:30","12:15","16:45"];
constmyRe=/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;constresults=myRe.exec("The date and time are 2009-09-08 09:37:08.");if(results){console.log("Matched: "+results[0]);// Entire matchconstmy_date=results[1];// First group == "2009-09-08"constmy_time=results[2];// Second group == "09:37:08"console.log(`It is${my_time} on${my_date}`);}elseconsole.log("Did not find a valid date!");
Every function in JavaScript is an instance of theFunction
constructor:
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.constadd=newFunction('x','y','return x + y');add(1,2);// => 3
The add function above may also be defined using a function expression:
constadd=function(x,y){returnx+y;};add(1,2);// => 3
In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain thethis
of the global object instead of inheriting it from where it was called / what it was called on, unlike thefunction() {}
expression.
constadd=(x,y)=>{returnx+y;};// values can also be implicitly returned (i.e. no return statement is needed)constaddImplicit=(x,y)=>x+y;add(1,2);// => 3addImplicit(1,2)// => 3
For functions that need to be hoisted, there is a separate expression:
functionadd(x,y){returnx+y;}add(1,2);// => 3
Hoisting allows users to use the function before it is "declared":
add(1,2);// => 3, not a ReferenceErrorfunctionadd(x,y){returnx+y;}
A function instance has properties and methods.
functionsubtract(x,y){returnx-y;}console.log(subtract.length);// => 2, arity of the function (number of arguments)console.log(subtract.toString());/*"function subtract(x, y) { return x - y;}"*/
The '+' operator isoverloaded: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number.
// Concatenate 2 stringsconsole.log('He'+'llo');// displays Hello// Add two numbersconsole.log(2+6);// displays 8// Adding a number and a string results in concatenation (from left to right)console.log(2+'2');// displays 22console.log('$'+3+4);// displays $34, but $7 may have been expectedconsole.log('$'+(3+4));// displays $7console.log(3+4+'7');// displays 77, numbers stay numbers until a string is added// Convert a string to a number using the unary plusconsole.log(+'2'===2);// displays trueconsole.log(+'Hello');// displays NaN
Similarly, the '*' operator is overloaded: it can convert a string into a number.
console.log(2+'6'*1);// displays 8console.log(3*'7');// 21console.log('3'*'7');// 21console.log('hello'*'world');// displays NaN
JavaScript supports the followingbinary arithmetic operators:
+ | addition |
- | subtraction |
* | multiplication |
/ | division (returns a floating-point value) |
% | modulo (returns the remainder) |
** | exponentiation |
JavaScript supports the followingunary arithmetic operators:
+ | unary conversion of string to number |
- | unary negation (reverses the sign) |
++ | increment (can be prefix or postfix) |
-- | decrement (can be prefix or postfix) |
letx=1;console.log(++x);// x becomes 2; displays 2console.log(x++);// displays 2; x becomes 3console.log(x);// x is 3; displays 3console.log(x--);// displays 3; x becomes 2console.log(x);// displays 2; x is 2console.log(--x);// x becomes 1; displays 1
The modulo operator displays the remainder after division by the modulus. If negative numbers are involved, the returned value depends on the operand.
constx=17;console.log(x%5);// displays 2console.log(x%6);// displays 5console.log(-x%5);// displays -2console.log(-x%-5);// displays -2console.log(x%-5);// displays 2
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again:
constx=17;console.log((-x%5+5)%5);// displays 3
Users could also do:
constx=17;console.log(Math.abs(-x%5));// also 3
= | assign |
+= | add and assign |
-= | subtract and assign |
*= | multiply and assign |
/= | divide and assign |
%= | modulo and assign |
**= | exponentiation and assign |
letx=9;x+=1;console.log(x);// displays: 10x*=30;console.log(x);// displays: 300x/=6;console.log(x);// displays: 50x-=3;console.log(x);// displays: 47x%=7;console.log(x);// displays: 5
Assignment of object types
/** * To learn JavaScript objects... */constobject_1={a:1};// assign reference of newly created object to object_1letobject_2={a:0};letobject_3=object_2;// object_3 references the same object as object_2 doesobject_3.a=2;message();// displays 1 2 2object_2=object_1;// object_2 now references the same object as object_1// object_3 still references what object_2 referenced beforemessage();// displays 1 1 2object_2.a=7;// modifies object_1message();// displays 7 7 2object_3.a=5;// object_3 does not change object_2message();// displays 7 7 5object_3=object_2;object_3.a=4;// object_3 changes object_1 and object_2message();// displays 4 4 4/** * Prints the console.log message */functionmessage(){console.log(object_1.a+" "+object_2.a+" "+object_3.a);}
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.
leta,b,c,d,e;[a,b,c]=[3,4,5];console.log(`${a},${b},${c}`);// displays: 3,4,5e={foo:5,bar:6,baz:['Baz','Content']};constarr=[];({baz:[arr[0],arr[3]],foo:a,bar:b}=e);console.log(`${a},${b},${arr}`);// displays: 5,6,Baz,,,Content[a,b]=[b,a];// swap contents of a and bconsole.log(a+','+b);// displays: 6,5[a,b,c]=[3,4,5];// permutations[a,b,c]=[b,c,a];console.log(`${a},${b},${c}`);// displays: 4,5,3
The ECMAScript 2015 standard introduced the "...
" array operator, for the related concepts of "spread syntax"[16] and "rest parameters".[17] Object spreading was added in ECMAScript 2018.
Spread syntax provides another way to destructure arrays and objects. For arrays, it indicates that the elements should be used as the parameters in a function call or the items in an array literal. For objects, it can be used for merging objects together or overriding properties.
In other words, "...
" transforms "[...foo]
" into "[foo[0], foo[1], foo[2]]
", and "this.bar(...foo);
" into "this.bar(foo[0], foo[1], foo[2]);
", and "{ ...bar }
" into{ prop: bar.prop, prop2: bar.prop2 }
.
consta=[1,2,3,4];// It can be used multiple times in the same expressionconstb=[...a,...a];// b = [1, 2, 3, 4, 1, 2, 3, 4];// It can be combined with non-spread items.constc=[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.constd=[a,a];// d = [[1, 2, 3, 4], [1, 2, 3, 4]]// It works the same with function callsfunctionfoo(arg1,arg2,arg3){console.log(`${arg1}:${arg2}:${arg3}`);}// Users can use it even if it passes more parameters than the function will usefoo(...a);// "1:2:3" → foo(a[0], a[1], a[2], a[3]);// Users can mix it with non-spread parametersfoo(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"constbar={a:1,b:2,c:3};// This would copy the objectconstcopy={...bar};// copy = { a: 1, b: 2, c: 3 };// "b" would be overridden hereconstoverride={...bar,b:4};// override = { a: 1, c: 3, b: 4 }
When...
is used in a functiondeclaration, it indicates arest parameter. The rest parameter must be the final named parameter in the function's parameter list. It will be assigned anArray
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).
functionfoo(a,b,...c){console.log(c.length);}foo(1,2,3,4,5);// "3" → c = [3, 4, 5]foo('a','b');// "0" → c = []
Rest parameters are similar to Javascript'sarguments
object, which is an array-like object that contains all of the parameters (named and unnamed) in the current function call. Unlikearguments
, however, rest parameters are trueArray
objects, so methods such as.slice()
and.sort()
can be used on them directly.
== | equal |
!= | not equal |
> | greater than |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
=== | identical (equal and of same type) |
!== | not identical |
Variables referencing objects are equal or identical only if they reference the same object:
constobj1={a:1};constobj2={a:1};constobj3=obj1;console.log(obj1==obj2);//falseconsole.log(obj3==obj1);//trueconsole.log(obj3===obj1);//true
See alsoString.
JavaScript provides four logical operators:
NOT = !a
)OR = a || b
) andconjunction (AND = a && b
)c ? t : f
)In the context of a logical operation, any expression evaluates to true except the following:
""
,''
,0
,-0
,NaN
,null
,undefined
,false
.The Boolean function can be used to explicitly convert to a primitive of typeBoolean
:
// Only empty strings return falseconsole.log(Boolean("")===false);console.log(Boolean("false")===true);console.log(Boolean("0")===true);// Only zero and NaN return falseconsole.log(Boolean(NaN)===false);console.log(Boolean(0)===false);console.log(Boolean(-0)===false);// equivalent to -1*0console.log(Boolean(-2)===true);// All objects return trueconsole.log(Boolean(this)===true);console.log(Boolean({})===true);console.log(Boolean([])===true);// These types return falseconsole.log(Boolean(null)===false);console.log(Boolean(undefined)===false);// equivalent to Boolean()
The NOT operator evaluates its operand as a Boolean and returns the negation. Using the operator twice in a row, as adouble negative, explicitly converts an expression to a primitive of type Boolean:
console.log(!0===Boolean(!0));console.log(Boolean(!0)===!!1);console.log(!!1===Boolean(1));console.log(!!0===Boolean(0));console.log(Boolean(0)===!1);console.log(!1===Boolean(!1));console.log(!""===Boolean(!""));console.log(Boolean(!"")===!!"s");console.log(!!"s"===Boolean("s"));console.log(!!""===Boolean(""));console.log(Boolean("")===!"s");console.log(!"s"===Boolean(!"s"));
The ternary operator can also be used for explicit conversion:
console.log([]==false);console.log([]?true:false);// “truthy”, but the comparison uses [].toString()console.log([0]==false);console.log([0]?true:false);// [0].toString() == "0"console.log("0"==false);console.log("0"?true:false);// "0" → 0 ... (0 == 0) ... 0 ← falseconsole.log([1]==true);console.log([1]?true:false);// [1].toString() == "1"console.log("1"==true);console.log("1"?true:false);// "1" → 1 ... (1 == 1) ... 1 ← trueconsole.log([2]!=true);console.log([2]?true:false);// [2].toString() == "2"console.log("2"!=true);console.log("2"?true:false);// "2" → 2 ... (2 != 1) ... 1 ← true
Expressions that use features such as post–incrementation (i++
) have an anticipatedside effect. JavaScript providesshort-circuit evaluation of expressions; the right operand is only executed if the left operand does not suffice to determine the value of the expression.
console.log(a||b);// When a is true, there is no reason to evaluate b.console.log(a&&b);// When a is false, there is no reason to evaluate b.console.log(c?t:f);// When c is true, there is no reason to evaluate f.
In early versions of JavaScript andJScript, the binary logical operators returned a Boolean value (like most C-derived programming languages). However, all contemporary implementations return one of their operands instead:
console.log(a||b);// if a is true, return a, otherwise return bconsole.log(a&&b);// if a is false, return a, otherwise return b
Programmers who are more familiar with the behavior in C might find this feature surprising, but it allows for a more concise expression of patterns likenull coalescing:
consts=t||"(default)";// assigns t, or the default value, if t is null, empty, etc.
??= | Nullish assignment |
||= | Logical Or assignment |
&&= | Logical And assignment |
JavaScript supports the followingbinarybitwise operators:
& | AND |
| | OR |
^ | XOR |
! | NOT |
<< | shift left (zero fill at right) |
>> | shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the left |
>>> | shift right (zero fill at left). For positive numbers,>> and>>> yield the same result. |
Examples:
constx=11&6;console.log(x);// 2
JavaScript supports the followingunary bitwise operator:
~ | NOT (inverts the bits) |
JavaScript supports the followingbinary assignment operators:
&= | and |
|= | or |
^= | xor |
<<= | shift left (zero fill at right) |
>>= | shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the left |
>>>= | shift right (zero fill at left). For positive numbers,>>= and>>>= yield the same result. |
Examples:
letx=7;console.log(x);// 7x<<=3;console.log(x);// 7->14->28->56
= | assignment |
+ | concatenation |
+= | concatenate and assign |
Examples:
letstr="ab"+"cd";// "abcd"str+="e";// "abcde"conststr2="2"+2;// "22", not "4" or 4.
JavaScript's nearest operator is??
, the "nullish coalescing operator", which was added to the standard inECMAScript's 11th edition.[18] In earlier versions, it could be used via aBabel plugin, and inTypeScript. It evaluates its left-hand operand and, if the result value isnot "nullish" (null
orundefined
), takes that value as its result; otherwise, it evaluates the right-hand operand and takes the resulting value as its result.
In the following example,a
will be assigned the value ofb
if the value ofb
is notnull
orundefined
, otherwise it will be assigned 3.
consta=b??3;
Before the nullish coalescing operator, programmers would use the logical OR operator (||
). But where??
looks specifically fornull
orundefined
, the||
operator looks for anyfalsy value:null
,undefined
,""
,0
,NaN
, and of course,false
.
In the following example,a
will be assigned the value ofb
if the value ofb
istruthy, otherwise it will be assigned 3.
consta=b||3;
A pair of curly brackets{ }
and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
if(expr){//statements;}elseif(expr2){//statements;}else{//statements;}
The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to theif statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions whatif is to statements.
constresult=condition?expression:alternative;
is the same as:
if(condition){constresult=expression;}else{constresult=alternative;}
Unlike theif statement, the conditional operator cannot omit its "else-branch".
The syntax of the JavaScriptswitch statement is as follows:
switch(expr){caseSOMEVALUE:// statements;break;caseANOTHERVALUE:// statements for when ANOTHERVALUE || ORNAOTHERONE// no break statement, falling through to the following casecaseORANOTHERONE:// statements specific to ORANOTHERONE (i.e. !ANOTHERVALUE && ORANOTHER);break;//The buck stops here.caseYETANOTHER:// statements;break;default:// statements;break;}
break;
is optional; however, it is usually needed, since otherwise code execution will continue to the body of the next case block. Thisfall through behavior can be used when the same set of statements apply in several cases, effectively creating adisjunction between those cases.The syntax of the JavaScriptfor loop is as follows:
for(initial;condition;loopstatement){/* statements will be executed every time the for{} loop cycles, while the condition is satisfied */}
or
for(initial;condition;loopstatement(iteration))// one statement
The syntax of the JavaScriptfor ... in loop
is as follows:
for(varproperty_nameinsome_object){// statements using some_object[property_name];}
if(some_object.hasOwnProperty(property_name)){...}
. Thus, adding a method to the array prototype withArray.prototype.newMethod=function(){...}
may causefor ... in
loops to loop over the method's name.The syntax of the JavaScriptwhile loop is as follows:
while(condition){statement1;statement2;statement3;...}
The syntax of the JavaScriptdo ... while loop
is as follows:
do{statement1;statement2;statement3;...}while(condition);
The with statement adds all of the given object's properties and methods into the following block's scope, letting them be referenced as if they were local variables.
with(document){consta=getElementById('a');constb=getElementById('b');constc=getElementById('c');};
The semantics are similar to the with statement ofPascal.
Because the availability of with statements hinders program performance and is believed to reduce code clarity (since any given variable could actually be a property from an enclosingwith), this statement is not allowed instrict mode.
JavaScript supports nested labels in most implementations. Loops or blocks can be labeled for the break statement, and loops forcontinue
. Althoughgoto
is a reserved word,[19]goto
is not implemented in JavaScript.
loop1:for(leta=0;a<10;++a){if(a===4)breakloop1;// Stops after the 4th attemptconsole.log('a = '+a);loop2:for(letb=0;b<10;++b){if(b===3)continueloop2;// Number 3 is skippedif(b===6)continueloop1;// Continues the first loop, 'finished' is not shownconsole.log('b = '+b);}//end of loop2console.log('finished');}//end of loop1block1:{console.log('Hello');// Displays 'Hello'breakblock1;console.log('World');// Will never get here}gotoblock1;// Parse error.
Afunction is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If a user exits the function without a return statement, the valueundefined is returned.
functiongcd(number1,number2){if(isNaN(number1*number2))throwTypeError("Non-Numeric arguments not allowed.");number1=Math.round(number1);number2=Math.round(number2);letdifference=number1-number2;if(difference===0)returnnumber1;returndifference>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.letmygcd=gcd;// mygcd and gcd reference the same function.console.log(mygcd(60,40));// 20
Functions arefirst class objects 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 valueundefined (that can be implicitly cast to false). Within the function, the arguments may also be accessed through thearguments object; this provides access to all arguments using indices (e.g.arguments[0],arguments[1],...arguments[n]
), including those beyond the number of named arguments. (While the arguments list has a.length
property, it isnot an instance ofArray; it does not have methods such as.slice(),.sort(), etc.)
functionadd7(x,y){if(!y){y=7;}console.log(x+y+arguments.length);};add7(3);// 11add7(3,4);// 9
Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed.
constobj1={a:1};constobj2={b:2};functionfoo(p){p=obj2;// Ignores actual parameterp.b=arguments[1];}foo(obj1,3);// Does not affect obj1 at all. 3 is additional parameterconsole.log(`${obj1.a}${obj2.b}`);// writes 1 3
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore, they implement fullclosures by remembering the outer function's local variables even after the outer function has exited.
lett="Top";letbar,baz;functionfoo(){letf="foo var";bar=function(){console.log(f)};baz=function(x){f=x;};}foo();baz("baz arg");bar();// "baz arg" (not "foo var") even though foo() has exited.console.log(t);// Top
Ananonymous 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 themap function and is applied to each of the elements of the array.[20]
[1,2,3].map(function(x){returnx*2;);//returns [2,4,6][1,2,3].map((x)=>{returnx*2;});//same result
Agenerator function is signified placing an * after the keywordfunction and contains one or moreyield statements. The effect is to return a value and pause execution at the current state. Declaring an generator function returns an iterator. Subsequent calls toiterator.next() resumes execution until the nextyield. When the iterator returns without using a yield statement there are no more values and thedone property of the iterator is set totrue.[21]
With the exception ofiOS devices from Apple, generators are not implemented for browsers on mobile devices.[22]
function*generator(){yield"red";yield"green";yield"blue";}letiterator=generator();letcurrent;while(current=iterator.next().value)console.log(current);//displays red, green then blueconsole.log(iterator.next().done)//displays true
The await operator in JavaScript can only be used from inside an async function or at the top level of amodule. If the parameter is apromise, execution of the async function will resume when the promise is resolved (unless the promise is rejected, in which case an error will be thrown that can be handled with normal JavaScriptexception handling). If the parameter is not a promise, the parameter itself will be returned immediately.[23]
Many libraries provide promise objects that can also be used with await, as long as they match the specification for native JavaScript promises. However, promises from thejQuery library were not Promises/A+ compatible until jQuery 3.0.[24]
Below is an example (modified from this[25] article):
asyncfunctioncreateNewDoc(){letresponse=awaitdb.post({});// post a new docreturndb.get(response.id);// find by id}asyncfunctionmain(){try{letdoc=awaitcreateNewDoc();console.log(doc);}catch(err){console.log(err);}}main();
For convenience, types are normally subdivided intoprimitives andobjects. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values ("slots" inprototype-based programming terminology). Objects may be thought of asassociative arrays or hashes, and are often implemented using these data structures. However, objects have additional features, such as aprototype chain, which ordinary associative arrays do not have.
JavaScript has several kinds of built-in objects, namelyArray
,Boolean
,Date
,Function
,Math
,Number
,Object
,RegExp
andString
. Other objects are "host objects", defined not by the language, but by the runtime environment. For example, in a browser, typical host objects belong to the DOM (window, form, links, etc.).
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:
// ConstructorconstanObject=newObject();// Object literalconstobjectA={};constobjectA2={};// A != A2, {}s create new objects as copies.constobjectB={index1:'value 1',index2:'value 2'};// Custom constructor (see below)
Object literals and array literals allow one to easily create flexible data structures:
constmyStructure={name:{first:"Mel",last:"Smith"},age:33,hobbies:["chess","jogging"]};
This is the basis forJSON, which is a simple notation that uses JavaScript-like syntax for data exchange.
Amethod is simply a function that has been assigned to a property name of an object. Unlike many object-oriented languages, there is no distinction between a function definition and a method definition in object-related JavaScript. Rather, the distinction occurs during function calling; a function can be called as a method.
When called as a method, the standard local variablethis is just automatically set to the object instance to the left of the ".". (There are alsocall andapply methods that can setthis explicitly—some packages such asjQuery do unusual things withthis.)
In the example below, Foo is being used as a constructor. There is nothing special about a constructor - it is just a plain function that initializes an object. When used with thenew keyword, as is the norm,this is set to a newly created blank object.
Note that in the example below, Foo is simply assigning values to slots, some of which are functions. Thus it can assign different functions to different instances. There is no prototyping in this example.
functionpx(){returnthis.prefix+"X";}functionFoo(yz){this.prefix="a-";if(yz>0){this.pyz=function(){returnthis.prefix+"Y";};}else{this.pyz=function(){returnthis.prefix+"Z";};}this.m1=px;returnthis;}constfoo1=newFoo(1);constfoo2=newFoo(0);foo2.prefix="b-";console.log("foo1/2 "+foo1.pyz()+foo2.pyz());// foo1/2 a-Y b-Zfoo1.m3=px;// Assigns the function itself, not its evaluated result, i.e. not px()constbaz={"prefix":"c-"};baz.m4=px;// No need for a constructor to make an object.console.log("m1/m3/m4 "+foo1.m1()+foo1.m3()+baz.m4());// m1/m3/m4 a-X a-X c-Xfoo1.m2();// Throws an exception, because foo1.m2 does not exist.
Constructor functions simply assign values to slots of a newly created object. The values may be data or other functions.
Example: Manipulating an object:
functionMyObject(attributeA,attributeB){this.attributeA=attributeA;this.attributeB=attributeB;}MyObject.staticC="blue";// On MyObject Function, not objectconsole.log(MyObject.staticC);// blueconstobject=newMyObject('red',1000);console.log(object.attributeA);// redconsole.log(object.attributeB);// 1000console.log(object.staticC);// undefinedobject.attributeC=newDate();// add a new propertydeleteobject.attributeB;// remove a property of objectconsole.log(object.attributeB);// undefined
The constructor itself is referenced in the object's prototype'sconstructor slot. So,
functionFoo(){}// 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).constx=newFoo();// The above is almost equivalent toconsty={};y.constructor=Foo;y.constructor();// Exceptx.constructor==y.constructor;// truexinstanceofFoo;// trueyinstanceofFoo;// false// y's prototype is Object.prototype, not// Foo.prototype, since it was initialized with// {} instead of new Foo.// Even though Foo is set to y's constructor slot,// this is ignored by instanceof - only y's prototype's// constructor slot is considered.
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a specialprototype
property, as discussed in the "Inheritance" section below.)
Object deletion is rarely used as the scripting engine willgarbage collect objects that are no longer being referenced.
JavaScript supports inheritance hierarchies through prototyping in the manner ofSelf.
In the following example, theDerived class inherits from theBase class.Whend is created asDerived, the reference to the base instance ofBase is copied tod.base.
Derive does not contain a value foraBaseFunction, so it is retrieved fromaBaseFunctionwhenaBaseFunction is accessed. This is made clear by changing the value ofbase.aBaseFunction, which is reflected in the value ofd.aBaseFunction.
Some implementations allow the prototype to be accessed or set explicitly using the__proto__ slot as shown below.
functionBase(){this.anOverride=function(){console.log("Base::anOverride()");};this.aBaseFunction=function(){console.log("Base::aBaseFunction()");};}functionDerived(){this.anOverride=function(){console.log("Derived::anOverride()");};}constbase=newBase();Derived.prototype=base;// Must be before new Derived()Derived.prototype.constructor=Derived;// Required to make `instanceof` workconstd=newDerived();// Copies Derived.prototype to d instance's hidden prototype slot.dinstanceofDerived;// truedinstanceofBase;// truebase.aBaseFunction=function(){console.log("Base::aNEWBaseFunction()");};d.anOverride();// Derived::anOverride()d.aBaseFunction();// Base::aNEWBaseFunction()console.log(d.aBaseFunction==Derived.prototype.aBaseFunction);// trueconsole.log(d.__proto__==base);// true in Mozilla-based implementations and false in many others.
The following shows clearly how references to prototypes arecopied on instance creation, but that changes to a prototype can affect all instances that refer to it.
functionm1(){return"One";}functionm2(){return"Two";}functionm3(){return"Three";}functionBase(){}Base.prototype.m=m2;constbar=newBase();console.log("bar.m "+bar.m());// bar.m TwofunctionTop(){this.m=m3;}constt=newTop();constfoo=newBase();Base.prototype=t;// No effect on foo, the *reference* to t is copied.console.log("foo.m "+foo.m());// foo.m Twoconstbaz=newBase();console.log("baz.m "+baz.m());// baz.m Threet.m=m1;// Does affect baz, and any other derived classes.console.log("baz.m1 "+baz.m());// baz.m1 One
In practice many variations of these themes are used, and it can be both powerful and confusing.
JavaScript includes atry ... catch ... finally
exception handling statement to handle run-time errors.
Thetry ... catch ... finally
statement catchesexceptions resulting from an error or a throw statement. Its syntax is as follows:
try{// Statements in which exceptions might be thrown}catch(errorValue){// Statements that execute in the event of an exception}finally{// Statements that execute afterward either way}
Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. The catch block canthrow(errorValue), if it does not want to handle a specific error.
In any case the statements in the finally block are always executed. This can be used to free resources, although memory is automatically garbage collected.
Either the catch or the finally clause may be omitted. The catch argument is required.
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used inJava:
try{statement;}catch(eife=="InvalidNameException"){statement;}catch(eife=="InvalidIdException"){statement;}catch(eife=="InvalidEmailException"){statement;}catch(e){statement;}
In a browser, theonerror event is more commonly used to trap exceptions.
onerror=function(errorValue,url,lineNr){...;returntrue;};
Evaluates the first parameter as an expression, which can include assignment statements. Variables local to functions can be referenced by the expression. However,eval
represents a major security risk, as it allows a bad actor to execute arbitrary code, so its use is discouraged.[27]
>(functionfoo(){...varx=7;...console.log("val "+eval("x + 2"));...})();val9undefined
Omitting semicolons is not a good programming practice; you should get into the habit of inserting them.
In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared.