Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
JavaScript
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Features == The following features are common to all conforming ECMAScript implementations unless explicitly specified otherwise. === Imperative and structured === {{Main|Structured programming}} JavaScript supports much of the [[structured programming]] syntax from [[C (computer language)|C]] (e.g., <code>if</code> statements, <code>while</code> loops, <code>switch</code> statements, <code>do while</code> loops, etc.). One partial exception is [[scope (computer science)|scoping]]: originally JavaScript only had [[function scoping]] with <code>var</code>; [[block scoping]] was added in ECMAScript 2015 with the keywords <code>let</code> and <code>[[const (computer programming)|const]]</code>. Like C, JavaScript makes a distinction between [[Expression (computer science)|expressions]] and [[Statement (computer science)|statements]]. One syntactic difference from C is [[Defensive semicolon|automatic semicolon insertion]], which allow semicolons (which terminate statements) to be omitted.<ref name="Flanagan2006">{{cite book|last=Flanagan|first=David|title=JavaScript: The Definitive Guide |url=https://books.google.com/books?id=2weL0iAfrEMC|date=August 17, 2006|publisher=[[O'Reilly Media, Inc.]]|isbn=978-0-596-55447-7|page=16|access-date=March 29, 2019|archive-date=August 1, 2020|archive-url=https://web.archive.org/web/20200801065235/https://books.google.com/books?id=2weL0iAfrEMC|url-status=live}}</ref> === Weakly typed === {{Main|Weakly typed}} JavaScript is [[Strong and weak typing|weakly typed]], which means certain types are implicitly cast depending on the operation used.<ref name="casting_rules">{{cite web |last=Korolev |first=Mikhail |date=2019-03-01 |title=JavaScript quirks in one image from the Internet |url=https://dev.to/mkrl/javascript-quirks-in-one-image-from-the-internet-52m7 |url-status=live |archive-url=https://web.archive.org/web/20191028204723/https://dev.to/mkrl/javascript-quirks-in-one-image-from-the-internet-52m7 |archive-date=October 28, 2019 |access-date=October 28, 2019 |website=The DEV Community |language=en}}</ref> * The binary <code>+</code> operator casts both operands to a string unless both operands are numbers. This is because the addition operator doubles as a concatenation operator * The binary <code>-</code> operator always casts both operands to a number * Both unary operators (<code>+</code>, <code>-</code>) always cast the operand to a number. However, <code>+</code> always casts to <code>Number</code> ([[Double-precision floating-point format|binary64]]) while <code>-</code> preserves <code>BigInt</code> ([[Arbitrary-precision arithmetic|integer]])<ref>{{cite web | url=https://github.com/tc39/proposal-bigint/blob/master/ADVANCED.md#dont-break-asmjs | title=Proposal-bigint/ADVANCED.md at master Β· tc39/Proposal-bigint | website=[[GitHub]] }}</ref> Values are cast to strings like the following:<ref name="casting_rules" /> * Strings are left as-is * Numbers are converted to their string representation * Arrays have their elements cast to strings after which they are joined by commas (<code>,</code>) * Other objects are converted to the string <code>[object Object]</code> where <code>Object</code> is the name of the constructor of the object Values are cast to numbers by casting to strings and then casting the strings to numbers. These processes can be modified by defining <code>toString</code> and <code>valueOf</code> functions on the [[#Object-orientation (prototype-based)|prototype]] for string and number casting respectively. JavaScript has received criticism for the way it implements these conversions as the complexity of the rules can be mistaken for inconsistency.<ref>{{cite web |date=2012 |title=Wat |url=https://www.destroyallsoftware.com/talks/wat |url-status=live |archive-url=https://web.archive.org/web/20191028204723/https://www.destroyallsoftware.com/talks/wat |archive-date=October 28, 2019 |access-date=October 28, 2019 |website=Destroy All Software |first1=Gary |last1=Bernhardt }}</ref><ref name="casting_rules" /> For example, when adding a number to a string, the number will be cast to a string before performing concatenation, but when subtracting a number from a string, the string is cast to a number before performing subtraction. {| class="wikitable" |+JavaScript type conversions !left operand !operator !right operand !result |- |<code>[]</code> (empty array) |<code>+</code> |<code>[]</code> (empty array) |<code>""</code> (empty string) |- |<code>[]</code> (empty array) |<code>+</code> |<code>{}</code> (empty object) |<code>"[object Object]"</code> (string) |- |<code>false</code> (boolean) |<code>+</code> |<code>[]</code> (empty array) |<code>"false"</code> (string) |- |<code>"123"</code>(string) |<code>+</code> |<code>1</code> (number) |<code>"1231"</code> (string) |- |<code>"123"</code> (string) |<code>-</code> |<code>1</code> (number) |<code>122</code> (number) |- |<code>"123"</code> (string) |<code>-</code> |<code>"abc"</code> (string) |<code>[[NaN]]</code> (number) |} Often also mentioned is <code>{} + []</code> resulting in <code>0</code> (number). This is misleading: the <code>{}</code> is interpreted as an empty code block instead of an empty object, and the empty array is cast to a number by the remaining unary <code>+</code> operator. If the expression is wrapped in parentheses - <code>({} + [])</code> β the curly brackets are interpreted as an empty object and the result of the expression is <code>"[object Object]"</code> as expected.<ref name="casting_rules" /> === Dynamic === {{Main|Dynamic Programming}} ==== Typing ==== {{Main|Dynamic typing}} JavaScript is [[dynamic typing|dynamically typed]] like most other [[scripting language]]s. A [[type system|type]] is associated with a [[value (computer science)|value]] rather than an expression. For example, a [[Variable (programming)|variable]] initially bound to a number may be reassigned to a [[string (computer science)|string]].<ref>{{cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures|title=JavaScript data types and data structures |date=February 16, 2017|website=MDN |access-date=February 24, 2017|archive-date=March 14, 2017|archive-url=https://web.archive.org/web/20170314230542/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures|url-status=live}}</ref> JavaScript supports various ways to test the type of objects, including [[duck typing]].{{Sfn|Flanagan|2006|pp=176β178}} ==== Run-time evaluation ==== {{Main|eval}} JavaScript includes an <code>[[eval]]</code> function that can execute statements provided as strings at run-time. === Object-orientation (prototype-based) === Prototypal inheritance in JavaScript is described by [[Douglas Crockford]] as: {{Blockquote |You make prototype objects, and then ... make new instances. Objects are mutable in JavaScript, so we can augment the new instances, giving them new fields and methods. These can then act as prototypes for even newer objects. We don't need classes to make lots of similar objects... Objects inherit from objects. What could be more object oriented than that?<ref>{{cite web|last=Crockford|first=Douglas|title=Prototypal Inheritance in JavaScript|url=https://javascript.crockford.com/prototypal.html|access-date=20 August 2013|archive-date=13 August 2013|archive-url=https://web.archive.org/web/20130813163035/https://javascript.crockford.com/prototypal.html|url-status=live}}</ref> }} In JavaScript, an [[Object (computer science)|object]] is an [[associative array]], augmented with a prototype (see below); each key provides the name for an object [[Property (programming)|property]], and there are two syntactical ways to specify such a name: dot notation (<code>obj.x = 10</code>) and bracket notation (<code>obj["x"] = 10</code>). A property may be added, rebound, or deleted at run-time. Most [[property (programming)|properties]] of an object (and any property that belongs to an object's prototype inheritance chain) can be enumerated using a <code>for...in</code> loop. ==== Prototypes ==== {{Main|Prototype-based programming}} JavaScript uses [[prototype-based programming|prototypes]] where many other object-oriented languages use [[Class (computer science)|classes]] for [[Inheritance (object-oriented programming)|inheritance]],<ref>{{cite web|title=Inheritance and the prototype chain|url=https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain|work=[[Mozilla]] Developer Network |access-date=April 6, 2013|archive-date=April 25, 2013|archive-url=https://web.archive.org/web/20130425144207/https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain|url-status=live}}</ref> but it's still possible to simulate most class-based features with the prototype system.<ref>{{cite book|last=Herman|first=David|title=Effective JavaScript|year=2013|publisher=Addison-Wesley|isbn=978-0-321-81218-6|page=83 |url=https://books.google.com/books?id=Nz9iAwAAQBAJ&pg=PA83 }}</ref> Additionally, [[ECMAScript |ECMAScript version 6]] (released June 2015) introduced the keywords '''class''', '''extends''' and '''super''', which serve as syntactic sugar to abstract the underlying prototypal inheritance system with a more conventional interface. Constructors are declared by specifying a method named '''constructor''', and all classes are automatically subclasses of the base class Object, similarly to Java. <syntaxhighlight lang="javascript"> class Person { constructor(name) { this.name = name; } } class Student extends Person { constructor(name, id) { super(name); this.id = id; } } const bob = new Student("Robert", 12345); console.log(bob.name); // Robert </syntaxhighlight>Though the underlying object mechanism is still based on prototypes, the newer syntax is similar to other object oriented languages. Private variables are declared by prefixing the field name with a [[number sign]] (#), and [[Polymorphism (computer science)|polymorphism]] is not directly supported, although it can be emulated by manually calling different functions depending on the number and type of arguments provided.<ref name="JavaScriptNext">{{cite book |last=Ghandi |first=Raju |date=2019 |title=JavaScript Next|location=New York City |publisher=Apress Media |pages=159β171 |isbn=978-1-4842-5394-6}}</ref> ==== Functions as object constructors ==== Functions double as object constructors, along with their typical role. Prefixing a function call with ''new'' will create an instance of a prototype, inheriting properties and methods from the constructor (including properties from the <code>Object</code> prototype).<ref name="Haverbeke2024">{{Cite book |title=Eloquent JavaScript |last=Haverbeke |first=Marijn |publisher=[[No Starch Press]] |isbn=978-1-71850-411-0 |edition=4th |location=San Francisco |publication-date=September 2024 |pages=[https://eloquentjavascript.net/Eloquent_JavaScript.pdf#section*.204 97β98] |language=en |url=https://eloquentjavascript.net/Eloquent_JavaScript.pdf |archive-url=https://web.archive.org/web/20250312193854/https://eloquentjavascript.net/Eloquent_JavaScript.pdf |archive-date=2025-03-12 |url-status=live}}</ref> ECMAScript 5 offers the <code>Object.create</code> method, allowing explicit creation of an instance without automatically inheriting from the <code>Object</code> prototype (older environments can assign the prototype to <code>null</code>).<ref>{{cite web|last=Katz|first=Yehuda|title=Understanding "Prototypes" in JavaScript|date=12 August 2011|url=https://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/|access-date=April 6, 2013|archive-date=5 April 2013|archive-url=https://web.archive.org/web/20130405154842/https://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/|url-status=live}}</ref> The constructor's <code>prototype</code> property determines the object used for the new object's internal prototype. New methods can be added by modifying the prototype of the function used as a constructor.<syntaxhighlight lang="javascript">// This code is completely equivalent to the previous snippet function Person(name) { this.name = name; } function Student(name, id) { Person.call(this, name); this.id = id; } var bob = new Student("Robert", 12345); console.log(bob.name); // Robert</syntaxhighlight>JavaScript's built-in classes, such as <code>Array</code> and <code>Object</code>, also have prototypes that can be modified. However, it's generally considered bad practice to [[Monkey patch|modify built-in objects]], because third-party code may use or inherit methods and properties from these objects, and may not expect the prototype to be modified.<ref>{{cite book |last=Herman |first=David |url=https://books.google.com/books?id=Nz9iAwAAQBAJ&pg=PA125 |title=Effective JavaScript |publisher=Addison-Wesley |year=2013 |isbn=978-0-321-81218-6 |pages=125β127}}</ref> ==== Functions as methods ==== {{Main|Method (computer science)}} <!--not sure where to classify this under--> Unlike in many object-oriented languages, in JavaScript there is no distinction between a function definition and a [[method (computer science)|method]] definition. Rather, the distinction occurs during function calling. When a function is called as a method of an object, the function's local ''this'' keyword is bound to that object for that invocation. === Functional === {{Main|Functional programming}} JavaScript [[Subroutine|functions]] are [[first-class function|first-class]]; a function is considered to be an object.<ref>{{cite web|title=Function β JavaScript|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function|access-date=2021-10-30|website=[[MDN Web Docs]]|language=en-US}}</ref> As such, a function may have properties and methods, such as <code>.call()</code> and <code>.bind()</code>.<ref>{{cite web | url=https://es5.github.com/#x15.3.4-toc | title=Properties of the Function Object | publisher=Es5.github.com | access-date=May 26, 2013 | archive-date=January 28, 2013 | archive-url=https://web.archive.org/web/20130128185825/https://es5.github.com/#x15.3.4-toc | url-status=live }}</ref> ==== Lexical closure ==== {{Main|Closure (computer programming)}} A ''nested'' function is a function defined within another function. It is created each time the outer function is invoked. In addition, each nested function forms a [[Closure (computer programming)|lexical closure]]: the [[Scope (programming)#Lexical scoping vs. dynamic scoping|lexical scope]] of the outer function (including any constant, local variable, or argument value) becomes part of the internal state of each inner function object, even after execution of the outer function concludes.{{Sfn|Flanagan|2006|p=141}} ==== Anonymous function ==== {{Main|Anonymous function}} JavaScript also supports [[anonymous function]]s. === Delegative === {{Main|Delegation (object-oriented programming)}} JavaScript supports implicit and explicit [[Delegation (object-oriented programming)|delegation]]. ==== Functions as roles (Traits and Mixins) ==== {{Main|Role-oriented programming|Traits (computer science)|Mixin}} JavaScript natively supports various function-based implementations of [[Role-oriented programming|Role]]<ref>[https://peterseliger.blogspot.de/2014/04/the-many-talents-of-javascript.html#the-many-talents-of-javascript-for-generalizing-role-oriented-programming-approaches-like-traits-and-mixins The many talents of JavaScript for generalizing Role-Oriented Programming approaches like Traits and Mixins] {{Webarchive|url=https://web.archive.org/web/20171005050713/https://peterseliger.blogspot.de/2014/04/the-many-talents-of-javascript.html#the-many-talents-of-javascript-for-generalizing-role-oriented-programming-approaches-like-traits-and-mixins |date=2017-10-05 }}, Peterseliger.blogspot.de, April 11, 2014.</ref> patterns like [[Traits (computer science)|Traits]]<ref>[https://soft.vub.ac.be/~tvcutsem/traitsjs/ Traits for JavaScript] {{Webarchive|url=https://web.archive.org/web/20140724052500/https://soft.vub.ac.be/~tvcutsem/traitsjs/ |date=2014-07-24 }}, 2010.</ref><ref>{{cite web |url=https://cocktailjs.github.io/ |title=Home | CocktailJS |website=Cocktailjs.github.io |access-date=February 24, 2017 |archive-date=February 4, 2017 |archive-url=https://web.archive.org/web/20170204083608/https://cocktailjs.github.io/ |url-status=live }}</ref> and [[Mixin]]s.<ref>{{cite web |url-status=live |first1=Angus |last1=Croll |url=https://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/ |title=A fresh look at JavaScript Mixins |archive-url=https://web.archive.org/web/20200415004603/https://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/ |archive-date=2020-04-15 |date=May 31, 2011 |website= JavaScript, JavaScriptβ¦ }}</ref> Such a function defines additional behavior by at least one method bound to the <code>this</code> keyword within its <code>function</code> body. A Role then has to be delegated explicitly via <code>call</code> or <code>apply</code> to objects that need to feature additional behavior that is not shared via the prototype chain. ==== Object composition and inheritance ==== Whereas explicit function-based delegation does cover [[Object composition|composition]] in JavaScript, implicit delegation already happens every time the prototype chain is walked in order to, e.g., find a method that might be related to but is not directly owned by an object. Once the method is found it gets called within this object's context. Thus [[Inheritance (object-oriented programming)|inheritance]] in JavaScript is covered by a delegation automatism that is bound to the prototype property of constructor functions. === Miscellaneous === ==== Zero-based numbering ==== JavaScript is a [[Zero-based numbering#Usage in programming languages|zero-index]] language. ==== Variadic functions ==== {{Main|Variadic function}} <!--note: this is not a functional programming feature--> An indefinite number of parameters can be passed to a function. The function can access them through [[formal parameter]]s and also through the local <code>arguments</code> object. [[Variadic functions]] can also be created by using the <code>[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind bind]</code> method. ==== Array and object literals ==== {{Main|Associative arrays|Object literal}} Like in many scripting languages, arrays and objects ([[associative arrays]] in other languages) can each be created with a succinct shortcut syntax. In fact, these [[Object literal|literals]] form the basis of the [[JSON]] data format. ==== Regular expressions ==== {{Main|Regular expression}} JavaScript supports [[regular expression]]s for text searches and manipulation.{{r|n=Haverbeke2024|p=139}} ===== Promises ===== {{Main|Futures and promises}} A built-in Promise object provides functionality for handling promises and associating handlers with an asynchronous action's eventual result. JavaScript supplies combinator methods, which allow developers to combine multiple JavaScript promises and do operations based on different scenarios. The methods introduced are: Promise.race, Promise.all, Promise.allSettled and Promise.any. ===== Async/await ===== {{Main|Async/await}} Async/await allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. Asynchronous, non-blocking code can be written, with minimal overhead, structured similarly to traditional synchronous, blocking code. === Vendor-specific extensions === Historically, some [[JavaScript engine]]s supported these non-standard features: * [[List comprehension|array comprehensions]] and generator expressions (like Python) * concise function expressions (<code>function(args) expr</code>; this experimental syntax predated arrow functions) * [[ECMAScript for XML]] (E4X), an extension that adds native XML support to ECMAScript (unsupported in Firefox since version 21<ref>{{cite web|title=E4X β Archive of obsolete content |url=https://developer.mozilla.org/en-US/docs/Archive/Web/E4X|website=Mozilla Developer Network|publisher=Mozilla Foundation|date=February 14, 2014|access-date=July 13, 2014|archive-date=July 24, 2014|archive-url=https://web.archive.org/web/20140724100129/https://developer.mozilla.org/en-US/docs/Archive/Web/E4X|url-status=dead}}</ref>)
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)