document.write
). Given that JavaScript is mainly used for alert
can also be used, but is not commonly used.
Origins
Basics
Case sensitivity
JavaScript isWhitespace and semicolons
Unlike in C, whitespace in JavaScript source can directly impact(
", open bracket " /
",_plus_"+
",_and_minus_"-
"._Of_these,_the_open_parenthesis_is_common_in_the_[/
",_plus_"+
",_and_minus_"-
"._Of_these,_the_open_parenthesis_is_common_in_the_immediately-invoked_function_expression">/code>",_slash_"/
",_plus_"+
",_and_minus_"-
"._Of_these,_the_open_parenthesis_is_common_in_the_immediately-invoked_function_expression_pattern,_and_open_bracket_occurs_sometimes,_while_others_are_quite_rare._An_example:
(
'_or_'[
',_so_the_line_is_not_accidentally_joined_with_the_previous_one._This_is_known_as_a_defensive_semicolon,_and_is_particularly_recommended,_because_code_may_otherwise_become_ambiguous_when_it_is_rearranged._For_example:
return
,_throw
,_break
,_continue
,_and_post-increment/decrement._In_all_cases,_inserting_semicolons_does_not_fix_the_problem,_but_makes_the_parsed_syntax_clear,_making_the_error_easier_to_detect._return
_and_throw
_take_an_optional_value,_while_break
_and_continue
_take_an_optional_label._In_all_cases,_the_advice_is_to_keep_the_value_or_label_on_the_same_line_as_the_statement._This_most_often_shows_up_in_the_return_statement,_where_one_might_return_a_large_object_literal,_which_might_be_accidentally_placed_starting_on_a_new_line._For_post-increment/decrement,_there_is_potential_ambiguity_with_pre-increment/decrement,_and_again_it_is_recommended_to_simply_keep_these_on_the_same_line.
_Comments
Comment_(computer_programming).html" "title="mmediately-invoked_function_expression.html" ;"title="/code>", slash "/
", plus "+
", and minus "-
". Of these, the open parenthesis is common in the immediately-invoked function expression">/code>", slash "/
", plus "+
", and minus "-
". Of these, the open parenthesis is common in the immediately-invoked function expression pattern, and open bracket occurs sometimes, while others are quite rare. An example:
(
' or '[
', so the line is not accidentally joined with the previous one. This is known as a defensive semicolon, and is particularly recommended, because code may otherwise become ambiguous when it is rearranged. For example:
return
, throw
, break
, continue
, and post-increment/decrement. In all cases, inserting semicolons does not fix the problem, but makes the parsed syntax clear, making the error easier to detect. return
and throw
take an optional value, while break
and continue
take an optional label. In all cases, the advice is to keep the value or label on the same line as the statement. This most often shows up in the return statement, where one might return a large object literal, which might be accidentally placed starting on a new line. For post-increment/decrement, there is potential ambiguity with pre-increment/decrement, and again it is recommended to simply keep these on the same line.
Comments
Comment (computer programming)">Comment Comment may refer to: * Comment (linguistics) or rheme, that which is said about the topic (theme) of a sentence * Bernard Comment (born 1960), Swiss writer and publisher Computing * Comment (computer programming), explanatory text or informa ...Variables
Variables in standard JavaScript have no type attached, so any value (each ''value'' has a type) can be stored in any variable. Starting with ES6, the 6th version of the language, variables could be declared withvar
for function scoped variables, and let
or const
which are for block level variables. Before ES6, variables could only be declared with a var
statement. Values assigned to variables declared with const
cannot be changed, but its properties can. A variable's identifier must start with a letter, underscore (_
), or dollar sign ($
), while subsequent characters can also be digits (0-9
). JavaScript is case sensitive, so the uppercase characters "A" through "Z" are different from the lowercase characters "a" through "z".
Starting with JavaScript 1.5, ISO 8859-1 or \uXXXX
Unicode escape sequences) can be used in identifiers. 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.
Scoping and hoisting
Variables declared withvar
are let
or const
have a block level scope. Since declarations are processed before any code is executed, a variable can be assigned to and used prior to being declared in the code. This is referred to as ', and it is equivalent to variables being forward declared at the top of the function or block.
With var
, let
, and const
statements, only the declaration is hoisted; assignments are not hoisted. Thus a statement in the middle of the function is equivalent to a declaration statement at the top of the function, and an assignment statement at that point in the middle of the function. This means that values cannot be accessed before they are declared; var
a variable's value is undefined
until it is initialized. Variables declared with let
or const
cannot be accessed until they have been initialized, so referencing such variables before will cause an error.
Function declarations, which declare a variable and assign a function to it, are similar to variable statements, but in addition to hoisting the declaration, they also hoist the assignment – as if the entire statement appeared at the top of the containing function – and thus forward reference is also possible: the location of a function statement within an enclosing function is irrelevant. This is different from a function expression being assigned to a variable in a var
, let
, or const
statement.
So, for example,
let
keyword.
Declaration and assignment
Variables declared outside a scope areReferenceError
exception.
When assigning an identifier, JavaScript goes through exactly the same process to retrieve this identifier, except that if it is not found in the ''global scope'', it will create the "variable" in the scope where it was created. As a consequence, a variable never declared will be global, if assigned. Declaring a variable (with the keyword var
) in the ''global scope'' (i.e. outside of any function body (or block in the case of let/const)), assigning a never declared identifier or adding a property to the ''global object'' (usually ''window'') will also create a new global variable.
Note that JavaScript's ''strict mode'' forbids the assignment of an undeclared variable, which avoids global namespace pollution.
Examples
Here are some examples of variable declarations and scope:Primitive data types
The JavaScript language provides six primitive data types: * Undefined * Number * BigInt * String * Boolean * Symbol Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries. These named values are described within the appropriate sections below.Undefined
The value of "undefined" is assigned to allisUndefined(my_var)
raises a if is an unknown identifier, whereas doesn't.
Number
Numbers are represented in binary asBigInt
BigInts can be used for arbitrarily largeString
A string in JavaScript is a sequence of characters. In JavaScript, strings can be created directly (as literals) by placing the series of characters between double (") or single (') quotes. Such strings must be written on a single line, but may include escaped newline characters (such as \n). The JavaScript standard allows the backquote character (`, a.k.a. grave accent or backtick) to quote multiline literal strings, but this is supported only on certain browsers as of 2016: Firefox and Chrome, but not Internet Explorer 11.Boolean
Type conversion
Automatic type coercion by the equality comparison operators (
and !=
) can be avoided by using the type checked comparison operators (
and !
).
When type conversion is required, JavaScript converts , , , or operands as follows:
;: 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.
;: If one of the operands is a Boolean, the Boolean operand is converted to 1 if it is , or to 0 if it is .
;: 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 or methods of the object. If this fails, a runtime error is generated.
a && b
), or , in the case of a , , b
); otherwise the right–operand is returned. Automatic type coercion by the comparison operators may differ for cases of mixed Boolean and number-compatible operands (including strings that can be evaluated as a number, or objects that can be evaluated as such a string), because the Boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a Boolean primitive by doubling the logical negation operator: (), using the function, or using the c ? t : f
).
Symbol
New in ECMAScript6. A ''Symbol'' is a unique and immutable identifier. Example:Symbol.iterator
; if something implements Symbol.iterator
, it's iterable:
Native objects
The JavaScript language provides a handful of native objects. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available.Array
AnArray
constructor specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (for example, join
, slice
, and push
).
As in the C family, arrays use a zero-based indexing scheme: A value that is inserted into an empty array by means of the push
method occupies the 0th index of the array.
length
property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated, if one creates a property with an even larger index. Writing a smaller number to the length
property will remove larger indices.
Elements of Array
s may be accessed using normal object property access notation:
Array
literal or the Array
constructor:
length
of the array will still be reported as 58. The maximum length of an array is 4,294,967,295 which corresponds to 32-bit binary number (11111111111111111111111111111111)2.
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
Date
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 the Date
constructor. Note that months are zero-based.
toString
:
Error
Custom error messages can be created using theError
class:
Math
The object contains various math-related constants (for example, ) and functions (for example, cosine). (Note that the object has no constructor, unlike or . All its methods are "static", that is "class" methods.) All the trigonometric functions use angles expressed inRegular expression
Character classes
Character matching
Repeaters
Anchors
Subexpression
Flags
Advanced methods
Capturing groups
Function
Every function in JavaScript is an instance of theFunction
constructor:
this
of the global object instead of inheriting it from where it was called / what it was called on, unlike the function()
expression.
Operators
The '+' operator is overloaded: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number.Arithmetic
JavaScript supports the following binary arithmetic operators: JavaScript supports the following unary arithmetic operators:Assignment
Destructuring assignment
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leaves that are to receive the substructures of the assigned value.Spread/rest operator
The ECMAScript 2015 standard introduces the "...
" operator, for the related concepts of "spread syntax" and "rest parameters"
Spread syntax provides another way to destructure arrays. It indicates that the elements in a specified array should be used as the parameters in a function call or the items in an array literal.
In other words, "...
" transforms " ..foo/code>" into " oo[0_foo[1.html"_;"title=".html"_;"title="oo[0">oo[0_foo[1">.html"_;"title="oo[0">oo[0_foo[1_foo[2.html" ;"title="">oo[0_foo[1.html" ;"title=".html" ;"title="oo[0">oo[0 foo[1">.html" ;"title="oo[0">oo[0 foo[1 foo[2">">oo[0_foo[1.html" ;"title=".html" ;"title="oo[0">oo[0 foo[1">.html" ;"title="oo[0">oo[0 foo[1 foo[2
", and "this.bar(...foo);
" into "this.bar(foo foo foo[2]);
".
var a = , 2, 3, 4
// It can be used multiple times in the same expression
var b = ..a, ...a // b = , 2, 3, 4, 1, 2, 3, 4
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
// It can be combined with non-spread items.
var c = , 6, ...a, 7, 9 // c = , 6, 1, 2, 3, 4, 7, 9
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
// For comparison, doing this without the spread operator
// creates a nested array.
var d = , a // d = 1, 2, 3, 4 , 2, 3, 4
// It works the same with function calls
function foo(arg1, arg2, arg3)
// You can use it even if it passes more parameters than the function will use
foo(...a); // "1:2:3" → foo(a a a a ;
// You can mix it with non-spread parameters
foo(5, ...a, 6); // "5:1:2" → foo(5, a a a a 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"
When ...
is used in a function ''declaration'', it indicates a rest parameter. The rest parameter must be the final named parameter in the function's parameter list. It will be assigned an Array
containing any arguments passed to the function in excess of the other named parameters. In other words, it gets "the rest" of the arguments passed to the function (hence the name).
function foo(a, b, ...c)
foo(1, 2, 3, 4, 5); // "3" → c = , 4, 5foo('a', 'b'); // "0" → c = []
Rest parameters are similar to Javascript's arguments
object, which is an array-like object that contains all of the parameters (named and unnamed) in the current function call. Unlike arguments
, however, rest parameters are true Array
objects, so methods such as .slice()
and .sort()
can be used on them directly.
The ...
operator can only be used with Array
objects. (However, there is a proposal to extend it to Object
s in a future ECMAScript standard.)
Comparison
Variables referencing objects are equal or identical only if they reference the same object:
var obj1 = ;
var obj2 = ;
var obj3 = obj1;
console.log(obj1 obj2); //false
console.log(obj3 obj1); //true
console.log(obj3 obj1); //true
See also String.
Logical
JavaScript provides four logical operators:
* unary negation (NOT = !a
)
* binary disjunction
In logic, disjunction is a logical connective typically notated as \lor and read aloud as "or". For instance, the English language sentence "it is raining or it is snowing" can be represented in logic using the disjunctive formula R \lor S ...
(OR = a , , b
) and conjunction
Conjunction may refer to:
* Conjunction (grammar), a part of speech
* Logical conjunction, a mathematical operator
** Conjunction introduction, a rule of inference of propositional logic
* Conjunction (astronomy), in which two astronomical bodies ...
(AND = a && b
)
* ternary conditional (c ? t : f
)
In the context of a logical operation, any expression evaluates to true except the following:
* Strings: ""
, ''
,
* Numbers: 0
, -0
, NaN
,
* Special: null
, undefined
,
* Boolean: false
.
The Boolean function can be used to explicitly convert to a primitive of type Boolean
:
// Only empty strings return false
console.log(Boolean("") false);
console.log(Boolean("false") true);
console.log(Boolean("0") true);
// Only zero and NaN return false
console.log(Boolean(NaN) false);
console.log(Boolean(0) false);
console.log(Boolean(-0) false); // equivalent to -1*0
console.log(Boolean(-2) true);
// All objects return true
console.log(Boolean(this) true);
console.log(Boolean() true);
console.log(Boolean([]) true);
// These types return false
console.log(Boolean(null) false);
console.log(Boolean(undefined) false); // equivalent to Boolean()
The NOT operator evaluates its operand as a Boolean and returns the negation. Using the operator twice in a row, as a double negative, explicitly converts an expression to a primitive of type Boolean:
console.log( !0 Boolean(!0));
console.log(Boolean(!0) !!1);
console.log(!!1 Boolean(1));
console.log(!!0 Boolean(0));
console.log(Boolean(0) !1);
console.log(!1 Boolean(!1));
console.log(!"" Boolean(!""));
console.log(Boolean(!"") !!"s");
console.log(!!"s" Boolean("s"));
console.log(!!"" Boolean(""));
console.log(Boolean("") !"s");
console.log(!"s" Boolean(!"s"));
The ternary operator can also be used for explicit conversion:
console.log([] false); console.log([] ? true : false); // “truthy”, but the comparison uses [].toString()
console.log( false); console.log( true : false); // toString() "0"
console.log("0" false); console.log("0"? true : false); // "0" → 0 ... (0 0) ... 0 ← false
console.log( true); console.log( true : false); // toString() "1"
console.log("1" true); console.log("1"? true : false); // "1" → 1 ... (1 1) ... 1 ← true
console.log( != true); console.log( true : false); // toString() "2"
console.log("2" != true); console.log("2"? true : false); // "2" → 2 ... (2 != 1) ... 1 ← true
Expressions that use features such as post–incrementation (i++
) have an anticipated side effect
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
. JavaScript provides short-circuit evaluation
A short circuit (sometimes abbreviated to short or s/c) is an electrical circuit that allows a current to travel along an unintended path with no or very low electrical impedance. This results in an excessive current flowing through the circuit. ...
of expressions; the right operand is only executed if the left operand does not suffice to determine the value of the expression.
console.log(a , , b); // When a is true, there is no reason to evaluate b.
console.log(a && b); // When a is false, there is no reason to evaluate b.
console.log(c ? t : f); // When c is true, there is no reason to evaluate f.
In early versions of JavaScript and JScript
JScript is Microsoft's legacy dialect of the ECMAScript standard that is used in Microsoft's Internet Explorer 11 and older.
JScript is implemented as an Active Scripting engine. This means that it can be "plugged in" to OLE Automation applic ...
, the binary logical operators returned a Boolean value (like most C-derived programming languages). However, all contemporary implementations return one of their operands instead:
console.log(a , , b); // if a is true, return a, otherwise return b
console.log(a && b); // if a is false, return a, otherwise return b
Programmers who are more familiar with the behavior in C might find this feature surprising, but it allows for a more concise expression of patterns like null coalescing:
var s = t , , "(default)"; // assigns t, or the default value, if t is null, empty, etc.
Logical assignment
Bitwise
JavaScript supports the following binary bitwise operators:
Examples:
x=11 & 6;
console.log(x); // 2
JavaScript supports the following unary bitwise operator:
Bitwise Assignment
JavaScript supports the following binary assignment operators:
Examples:
x=7;
console.log(x); // 7
x<<=3;
console.log(x); // 7->14->28->56
String
Examples:
str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
str2 = "2" + 2; // "22", not "4" or 4.
??
Control structures
Compound statements
A pair of curly brackets
and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
If ... else
if (expr) else if (expr2) else
Conditional (ternary) operator
The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the ''if'' statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what ''if'' is to statements.
result = condition ? expression : alternative;
is the same as:
if (condition) else
Unlike the ''if'' statement, the conditional operator cannot omit its "else-branch".
Switch statement
The syntax of the JavaScript switch statement is as follows:
switch (expr)
* break;
is optional; however, it is usually needed, since otherwise code execution will continue to the body of the next case block. This ''fall through'' behavior can be used when the same set of statements apply in several cases, effectively creating a disjunction
In logic, disjunction is a logical connective typically notated as \lor and read aloud as "or". For instance, the English language sentence "it is raining or it is snowing" can be represented in logic using the disjunctive formula R \lor S ...
between those cases.
* Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
* String literal values can also be used for the case values.
* Expressions can be used instead of values.
* The default case (optional) is executed when the expression does not match any other specified cases.
* Braces are required.
For loop
The syntax of the JavaScript for loop
In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied.
For-loops have two par ...
is as follows:
for (initial; condition; loop statement)
or
for (initial; condition; loop statement(iteration)) // one statement
For ... in loop
The syntax of the JavaScript for ... in loop
is as follows:
for (var property_name in some_object)
* 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 . Thus, adding a method to the array prototype with may cause for ... in
loops to loop over the method's name.
While loop
The syntax of the JavaScript while loop
In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The ''while'' loop can be thought of as a repeating if statement.
Overview
The ' ...
is as follows:
while (condition)
Do ... while loop
The syntax of the JavaScript do ... while loop
is as follows:
do while (condition);
With
The with statement adds all of the given object's properties and methods into the following block's scope, letting them be referenced as if they were local variables.
with (document) ;
* Note the absence of before each invocation.
The semantics are similar to the with statement of Pascal.
Because the availability of with statements hinders program performance and is believed to reduce code clarity (since any given variable could actually be a property from an enclosing ), this statement is not allowed in ''strict mode''.
Labels
JavaScript supports nested labels in most implementations. Loops or blocks can be labelled for the break statement, and loops for continue
. Although goto
is a reserved word,ECMA-262, Edition 3, 7.5.3 Future Reserved Words goto
is not implemented in JavaScript.
loop1: for (var a = 0; a < 10; ++a) //end of loop1
block1:
goto block1; // Parse error.
Functions
A function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-oriente ...
is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If you exit the function without a return statement, the value is returned.
function gcd(number1, number2)
console.log(gcd(60, 40)); // 20
//In the absence of parentheses following the identifier 'gcd' on the RHS of the assignment below,
//'gcd' returns a reference to the function itself without invoking it.
let mygcd = gcd; // mygcd and gcd reference the same function.
console.log(mygcd(60, 40)); // 20
Functions are first class object
In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include b ...
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 (that can be implicitly cast to false). Within the function, the arguments may also be accessed through the object; this provides access to all arguments using indices (e.g. ), including those beyond the number of named arguments. (While the arguments list has a .length
property, it is ''not'' an instance of ; it does not have methods such as , , etc.)
function add7(x, y) ;
add7(3); // 11
add7(3, 4); // 9
Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed.
var obj1 = ;
var obj2 = ;
function foo(p)
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
console.log(obj1.a + " " + obj2.b); // writes 1 3
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore, they implement full closures by remembering the outer function's local variables even after the outer function has exited.
let t = "Top";
let bar, baz;
function foo()
foo();
baz("baz arg");
bar(); // "baz arg" (not "foo var") even though foo() has exited.
console.log(t); // Top
Async/await
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
Prototype-based programming is a style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of reusing existing objects that serve as prototypes. This model can also be known as ''prototypa ...
terminology). Objects may be thought of as associative arrays
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an a ...
or hashes, and are often implemented using these data structures. However, objects have additional features, such as a prototype chain, which ordinary associative arrays do not have.
JavaScript has several kinds of built-in objects, namely Array
, Boolean
, Date
, Function
, Math
, Number
, Object
, RegExp
and String
. Other objects are "host objects", defined not by the language, but by the runtime environment. For example, in a browser, typical host objects belong to the DOM (window, form, links, etc.).
Creating objects
Objects can be created using a constructor or an object literal. The constructor can use either a built-in Object function or a custom function. It is a convention that constructor functions are given a name that starts with a capital letter:
// Constructor
var anObject = new Object();
// Object literal
var objectA = ;
var objectA2 = ; // A != A2, s create new objects as copies.
var objectB = ;
// Custom constructor (see below)
Object literals and array literals allow one to easily create flexible data structures:
var myStructure = ;
This is the basis for JSON, which is a simple notation that uses JavaScript-like syntax for data exchange.
Methods
A method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
is simply a function that has been assigned to a property name of an object. Unlike many object-oriented languages, there is no distinction between a function definition and a method definition in object-related JavaScript. Rather, the distinction occurs during function calling; a function can be called as a method.
When called as a method, the standard local variable ' is just automatically set to the object instance to the left of the "". (There are also ' and ' methods that can set ' explicitly—some packages such as jQuery
jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax. It is free, open-source software using the permissive MIT License. As of Aug 2022, jQuery is u ...
do unusual things with '.)
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 initialises an object. When used with the ' keyword, as is the norm, ' is set to a newly created blank object.
Note that in the example below, Foo is simply assigning values to slots, some of which are functions. Thus it can assign different functions to different instances. There is no prototyping in this example.
function px()
function Foo(yz)
var foo1 = new Foo(1);
var foo2 = new Foo(0);
foo2.prefix = "b-";
console.log("foo1/2 " + foo1.pyz() + foo2.pyz());
// foo1/2 a-Y b-Z
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px()
var baz = ;
baz.m4 = px; // No need for a constructor to make an object.
console.log("m1/m3/m4 " + foo1.m1() + foo1.m3() + baz.m4());
// m1/m3/m4 a-X a-X c-X
foo1.m2(); // Throws an exception, because foo1.m2 doesn't exist.
Constructors
Constructor functions simply assign values to slots of a newly created object. The values may be data or other functions.
Example: Manipulating an object:
function MyObject(attributeA, attributeB)
MyObject.staticC = "blue"; // On MyObject Function, not object
console.log(MyObject.staticC); // blue
object = new MyObject('red', 1000);
console.log(object.attributeA); // red
console.log(object attributeB"; // 1000
console.log(object.staticC); // undefined
object.attributeC = new Date(); // add a new property
delete object.attributeB; // remove a property of object
console.log(object.attributeB); // undefined
The constructor itself is referenced in the object's prototype's ''constructor'' slot. So,
function Foo()
// Use of 'new' sets prototype slots (for example,
// x = new Foo() would set x's prototype to Foo.prototype,
// and Foo.prototype has a constructor slot pointing back to Foo).
x = new Foo();
// The above is almost equivalent to
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 initialised with
// instead of new Foo.
// Even though Foo is set to y's constructor slot,
// this is ignored by instanceof - only y's prototype's
// constructor slot is considered.
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a special prototype
property, as discussed in the "Inheritance" section below.)
Object deletion is rarely used as the scripting engine will garbage collect objects that are no longer being referenced.
Inheritance
JavaScript supports inheritance hierarchies through prototyping in the manner of Self
The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhoo ...
.
In the following example, the class inherits from the class.
When is created as , the reference to the base instance of is copied to .
Derive does not contain a value for , so it is retrieved from ''when is accessed''. This is made clear by changing the value of , which is reflected in the value of .
Some implementations allow the prototype to be accessed or set explicitly using the slot as shown below.
function Base()
function Derived()
base = new Base();
Derived.prototype = base; // Must be before new Derived()
Derived.prototype.constructor = Derived; // Required to make `instanceof` work
d = new Derived(); // Copies Derived.prototype to d instance's hidden prototype slot.
d instanceof Derived; // true
d instanceof Base; // true
base.aBaseFunction = function()
d.anOverride(); // Derived::anOverride()
d.aBaseFunction(); // Base::aNEWBaseFunction()
console.log(d.aBaseFunction Derived.prototype.aBaseFunction); // true
console.log(d.__proto__ base); // true in Mozilla-based implementations and false in many others.
The following shows clearly how references to prototypes are ''copied'' on instance creation, but that changes to a prototype can affect all instances that refer to it.
function m1()
function m2()
function m3()
function Base()
Base.prototype.m = m2;
bar = new Base();
console.log("bar.m " + bar.m()); // bar.m Two
function Top()
t = new Top();
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
baz = new Base();
console.log("baz.m " + baz.m()); // baz.m Three
t.m = m1; // Does affect baz, and any other derived classes.
console.log("baz.m1 " + baz.m()); // baz.m1 One
In practice many variations of these themes are used, and it can be both powerful and confusing.
Exception handling
JavaScript includes a try ... catch ... finally
exception handling
In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
statement to handle run-time errors.
The try ... catch ... finally
statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:
try catch(errorValue) finally
Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. The catch block can , 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 in Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
:
try
catch (e if e "InvalidNameException")
catch (e if e "InvalidIdException")
catch (e if e "InvalidEmailException")
catch (e)
In a browser, the event is more commonly used to trap exceptions.
onerror = function (errorValue, url, lineNr) ;
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, represents a major security risk, as it allows a bad actor to execute arbitrary code, so its use is discouraged.
> (function foo() )();
val 9
undefined
See also
* Comparison of JavaScript-based source code editors
* JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
References
Further reading
* Danny Goodman: ''JavaScript Bible'', Wiley, John & Sons, .
* David Flanagan, Paula Ferguson: ''JavaScript: The Definitive Guide'', O'Reilly & Associates, .
* Thomas A. Powell, Fritz Schneider: ''JavaScript: The Complete Reference'', McGraw-Hill Companies, .
* Axel Rauschmayer: ''Speaking JavaScript: An In-Depth Guide for Programmers'', 460 pages, O'Reilly Media, 25 February 2014, .
free online edition
* Emily Vander Veer: ''JavaScript For Dummies, 4th Edition'', Wiley, .
External links
A re-introduction to JavaScript - Mozilla Developer Center
JavaScript Loops
* ECMAScript standard references
Interactive JavaScript Lessons - example-based
JavaScript on About.com: lessons and explanation
JavaScript Training
* Mozilla Developer Center Core References for JavaScript version
1.5
an
Mozilla JavaScript Language Documentation
{{DEFAULTSORT:Javascript Syntax
syntax
Programming language syntax