Array ( [0] => {{Short description|High-level programming language}} [1] => {{Use dmy dates|date=March 2024}} [2] => {{Distinguish|Java (programming language)|Javanese script|ECMAScript}} [3] => {{Redirect|.js|the Microsoft dialect used in Internet Explorer|JScript|}} [4] => {{For|the uses of JavaScript on Wikipedia|Wikipedia:WikiProject JavaScript|selfref=yes}} [5] => {{pp-semi-indef|small=yes}} [6] => [7] => {{Infobox programming language [8] => | name = JavaScript [9] => | logo = [10] => | logo alt = [11] => | screenshot = JavaScript code.png [12] => | screenshot caption = Screenshot of JavaScript source code [13] => | paradigm = [[Multi-paradigm]]: [[event-driven programming|event-driven]], [[functional programming|functional]], [[imperative programming|imperative]], [[procedural programming|procedural]], [[object-oriented programming|object-oriented]] [14] => | designer = [[Brendan Eich]] of [[Netscape]] initially; others have also contributed to the [[ECMAScript]] standard [15] => | typing = [[Dynamic typing|Dynamic]], [[Weak typing|weak]], [[Duck typing|duck]] [16] => | implementations = [[V8 (JavaScript engine)|V8]], [[JavaScriptCore]], [[SpiderMonkey (JavaScript engine)|SpiderMonkey]], [[Chakra (JScript engine)|Chakra]] [17] => | influenced = [[ActionScript]], [[ArkTS]], [[AssemblyScript]], [[CoffeeScript]], [[Dart (programming language)|Dart]], [[Haxe]], [[JS++]], [[Opa (programming language)|Opa]], [[TypeScript]] [18] => | license = [19] => | file extensions = {{flatlist| [20] => * .js [21] => * .cjs [22] => * .mjs{{cite web|url=https://github.com/nodejs/node-eps/blob/master/002-es-modules.md|title=nodejs/node-eps|website=GitHub|access-date=2018-07-05|archive-date=2020-08-29|archive-url=https://web.archive.org/web/20200829024713/https://github.com/nodejs/node-eps/blob/master/002-es-modules.md|url-status=live}} [23] => }} [24] => | file format = [25] => | wikibooks = JavaScript [26] => | year = {{start date and age|1995|12|4}}{{Cite press release |url=https://wp.netscape.com/newsref/pr/newsrelease67.html |archive-url=https://web.archive.org/web/20070916144913/https://wp.netscape.com/newsref/pr/newsrelease67.html |archive-date=2007-09-16 |title=Netscape and Sun announce JavaScript, the Open, Cross-platform Object Scripting Language for Enterprise Networks and the Internet |date=December 4, 1995}} [27] => | latest release version = {{wikidata|property|edit|reference|P548=Q2804309|P348}} [28] => | latest release date = {{start date and age|{{wikidata|qualifier|single|P548=Q2804309|P348|P577}}}} [29] => | latest preview version = {{wikidata|property|edit|reference|P548=Q51930650|P348}} [30] => | latest preview date = {{start date and age|{{wikidata|qualifier|single|P548=Q51930650|P348|P577}}}} [31] => | influenced by = [[Java (programming language)|Java]],{{cite book|last=Seibel|first=Peter|title=Coders at Work: Reflections on the Craft of Programming|isbn=9781430219484|quote="Eich: The immediate concern at Netscape was it must look like Java."|url=https://books.google.com/books?id=nneBa6-mWfgC&q=The+immediate+concern+at+Netscape+was+it+must+look+like+Java.&pg=PA141|access-date=December 25, 2018|date=September 16, 2009|publisher=Apress |archive-date=December 24, 2020|archive-url=https://web.archive.org/web/20201224233514/https://books.google.com/books?id=nneBa6-mWfgC&q=The+immediate+concern+at+Netscape+was+it+must+look+like+Java.&pg=PA141|url-status=live}} [[Scheme (programming language)|Scheme]], [[Self (programming language)|Self]],{{cite web|url=https://brendaneich.com/2008/04/popularity/|title = Popularity – Brendan Eich}} [[AWK]],{{cite web|title=Brendan Eich: An Introduction to JavaScript, JSConf 2010|website=[[YouTube]]|quote="Eich: "function", eight letters, I was influenced by AWK."|url=https://www.youtube.com/watch?v=1EyRscXrehw|access-date=November 25, 2019|page=22m|archive-date=August 29, 2020|archive-url=https://web.archive.org/web/20200829024704/https://www.youtube.com/watch?v=1EyRscXrehw|url-status=live}} [[HyperTalk]]{{cite book |last=Eich |first=Brendan |authorlink1=Brendan Eich |chapter=Foreword |editor1-last=Goodman |editor1-first=Danny |editor1-link=Danny Goodman |year=1998 |title=JavaScript Bible |edition=3rd |publisher=[[John Wiley & Sons]] |isbn=0-7645-3188-3 |lccn=97078208 |oclc=38888873 |ol=712205M |url-access=registration |url=https://archive.org/details/javascriptbible000good}} [32] => | website = {{URL|https://ecma-international.org/publications-and-standards/standards/ecma-262/}} [33] => }} [34] => [35] => '''JavaScript''' ({{IPAc-en|ˈ|dʒ|ɑː|v|ə|s|k|r|ɪ|p|t}}), often abbreviated as '''JS''', is a [[programming language]] and core technology of [[World Wide Web|the Web]], alongside [[HTML]] and [[CSS]]. 99% of [[website]]s use JavaScript on the [[Client (computing)|client]] side for [[Web page|webpage]] behavior.{{cite web |title=Usage Statistics of JavaScript as Client-side Programming Language on Websites |url=https://w3techs.com/technologies/details/cp-javascript |access-date=2024-02-27 |website=W3Techs }} [36] => [37] => [[Web browser]]s have a dedicated [[JavaScript engine]] that executes the client [[Source code|code]]. These engines are also utilized in some [[Server (computing)|servers]] and a variety of [[Application software|apps]]. The most popular [[runtime system]] for non-browser usage is [[Node.js]]. [38] => [39] => JavaScript is a [[High-level programming language|high-level]], often [[Just-in-time compilation|just-in-time compiled]] language that conforms to the [[ECMAScript]] standard.{{cite web|title=ECMAScript 2020 Language Specification|url=https://tc39.es/ecma262/#sec-overview|url-status=live|archive-url=https://web.archive.org/web/20200508053013/https://tc39.es/ecma262/#sec-overview|archive-date=2020-05-08|access-date=2020-05-08}} It has [[dynamic typing]], [[Prototype-based programming|prototype-based]] [[object-oriented programming|object-orientation]], and [[first-class function]]s. It is [[Programming paradigm|multi-paradigm]], supporting [[Event-driven programming|event-driven]], [[functional programming|functional]], and [[imperative programming|imperative]] [[programming paradigm|programming style]]s. It has [[application programming interface]]s (APIs) for working with text, dates, [[regular expression]]s, standard [[data structure]]s, and the [[Document Object Model]] (DOM). [40] => [41] => The ECMAScript standard does not include any [[input/output]] (I/O), such as [[computer network|networking]], [[data storage|storage]], or [[computer graphics|graphics]] facilities. In practice, the web browser or other runtime system provides JavaScript APIs for I/O. [42] => [43] => Although [[Java (programming language)|Java]] and JavaScript are similar in name, [[Syntax (programming languages)|syntax]], and respective [[Standard library|standard libraries]], the two languages are distinct and differ greatly in design. [44] => [45] => ==History== [46] => ===Creation at Netscape=== [47] => The first popular [[web browser]] with a [[graphical user interface]], [[Mosaic (web browser)|Mosaic]], was released in 1993. Accessible to non-technical people, it played a prominent role in the rapid growth of the early [[World Wide Web]].{{cite news |date=March 17, 2011 |title=Bloomberg Game Changers: Marc Andreessen |work=[[Bloomberg L.P.|Bloomberg]] |publisher=Bloomberg |url=https://www.bloomberg.com/video/67758394 |url-status=live |access-date=December 7, 2011 |archive-url=https://web.archive.org/web/20120516093712/https://www.bloomberg.com/video/67758394/ |archive-date=May 16, 2012}} The lead developers of Mosaic then founded the [[Netscape]] corporation, which released a more polished browser, [[Netscape Navigator]], in 1994. This quickly became the most-used.{{cite web|url=https://www.mwdwebsites.com/nj-web-design-web-browsers.html|title=The Evolution of the Web Browsers|last=Enzer|first=Larry|date=August 31, 2018|website=Monmouth Web Developers|access-date=August 31, 2018|archive-date=August 31, 2018|archive-url=https://web.archive.org/web/20180831174847/https://www.mwdwebsites.com/nj-web-design-web-browsers.html|url-status=dead}} [48] => [49] => During these formative years of the Web, [[web page]]s could only be static, lacking the capability for dynamic behavior after the page was loaded in the browser. There was a desire in the flourishing web development scene to remove this limitation, so in 1995, Netscape decided to add a [[programming language]] to Navigator. They pursued two routes to achieve this: collaborating with [[Sun Microsystems]] to embed the [[Java (programming language)|Java]] language, while also hiring [[Brendan Eich]] to embed the [[Scheme (programming language)|Scheme]] language.{{cite web|url=https://exploringjs.com/es5/ch04.html|title=Chapter 4. How JavaScript Was Created|website=speakingjs.com|access-date=2017-11-21|archive-date=2020-02-27|archive-url=https://web.archive.org/web/20200227184037/https://speakingjs.com/es5/ch04.html|url-status=live}} [50] => [51] => The goal was a "language for the masses", "to help nonprogrammers create dynamic, interactive [[website|Web sites]]"."Netscape Communications Corp.", Browser enhancements. Encyclopædia Britannica 2006 Ultimate Reference Suite DVD Netscape management soon decided that the best option was for Eich to devise a new language, with syntax similar to Java and less like Scheme or other extant [[scripting language]]s. Although the new language and its [[Interpreter (computing)|interpreter]] implementation were called LiveScript when first shipped as part of a Navigator [[beta software|beta]] in September 1995, the name was changed to JavaScript for the official release in December.{{cite web | archive-url=https://web.archive.org/web/20080208124612/https://wp.netscape.com/comprod/columns/techvision/innovators_be.html | archive-date=February 8, 2008 | title=TechVision: Innovators of the Net: Brendan Eich and JavaScript | url=https://wp.netscape.com/comprod/columns/techvision/innovators_be.html }} [52] => [53] => The choice of the JavaScript name has caused confusion, implying that it is directly related to Java. At the time, the [[Dot-com bubble|dot-com boom]] had begun and Java was a popular new language, so Eich considered the JavaScript name a marketing ploy by Netscape.{{Citation|last=Fin JS|title=Brendan Eich – CEO of Brave|date=June 17, 2016|url=https://www.youtube.com/watch?v=XOmhtfTrRxc |website=YouTube |access-date=February 7, 2018 }} [54] => [55] => ===Adoption by Microsoft=== [56] => [[Microsoft]] debuted [[Internet Explorer]] in 1995, leading to a [[browser war]] with Netscape. On the JavaScript front, Microsoft created its own [[Interpreter (computing)|interpreter]] called [[JScript]].{{cite web |title=Chapter 5. Standardization: ECMAScript |url=https://speakingjs.com/es5/ch05.html |website=speakingjs.com |access-date=1 November 2021 |archive-date=1 November 2021 |archive-url=https://web.archive.org/web/20211101184346/http://speakingjs.com/es5/ch05.html |url-status=dead }} [57] => [58] => Microsoft first released JScript in 1996, alongside initial support for [[CSS]] and extensions to [[HTML]]. Each of these [[implementation]]s was noticeably different from their counterparts in [[Netscape Navigator]].{{cite web |url=https://archive.oreilly.com/pub/a/javascript/2001/04/06/js_history.html |title=JavaScript, How Did We Get Here? |last=Champeon |first=Steve |date=April 6, 2001 |website=oreilly.com |access-date=July 16, 2016 |archive-url=https://web.archive.org/web/20160719020828/https://archive.oreilly.com/pub/a/javascript/2001/04/06/js_history.html |archive-date=July 19, 2016 |url-status=dead}}{{cite web |url=https://news.microsoft.com/1996/05/29/microsoft-internet-explorer-3-0-beta-now-available/ |title=Microsoft Internet Explorer 3.0 Beta Now Available |publisher=Microsoft |date=May 29, 1996 |website=microsoft.com |access-date=July 16, 2016 |archive-date=November 24, 2020 |archive-url=https://web.archive.org/web/20201124154053/https://news.microsoft.com/1996/05/29/microsoft-internet-explorer-3-0-beta-now-available/ |url-status=live }} These differences made it difficult for developers to make their websites work well in both browsers, leading to widespread use of "best viewed in Netscape" and "best viewed in Internet Explorer" logos for several years.{{cite web |url=https://www.technologizer.com/2010/09/16/the-unwelcome-return-of-best-viewed-with-internet-explorer/ |title=The Unwelcome Return of "Best Viewed with Internet Explorer" |last=McCracken |first=Harry |date=September 16, 2010 |website=technologizer.com |access-date=July 16, 2016 |archive-date=June 23, 2018 |archive-url=https://web.archive.org/web/20180623192402/https://www.technologizer.com/2010/09/16/the-unwelcome-return-of-best-viewed-with-internet-explorer/ |url-status=live }} [59] => [60] => ===The rise of JScript=== [61] => {{Quote box|[[Brendan Eich]] later said of this period: "It's still kind of a [[sidekick]] language. It's considered slow or annoying. People do [[Pop-up ad|pop-ups]] or those scrolling messages in the old [[status bar]] at the bottom of your old [[web browser|browser]]."|width=30%}} [62] => [63] => In November 1996, [[Netscape]] submitted JavaScript to [[Ecma International]], as the starting point for a standard specification that all browser vendors could conform to. This led to the official release of the first [[ECMAScript]] language specification in June 1997. [64] => [65] => The standards process continued for a few years, with the release of ECMAScript 2 in June 1998 and ECMAScript 3 in December 1999. Work on ECMAScript 4 began in 2000. [66] => [67] => However, the effort to fully standardize the language was undermined by [[Microsoft]] gaining an increasingly dominant position in the browser market. By the early 2000s, [[Internet Explorer]]'s market share reached 95%.{{cite news | url=https://www.searchenginejournal.com/mozilla-firefox-internet-browser-market-share-gains-to-74/1082/ | title=Mozilla Firefox Internet Browser Market Share Gains to 7.4% | first=Loren | last=Baker | work=Search Engine Journal | date=November 24, 2004 | access-date=May 8, 2021 | archive-date=May 7, 2021 | archive-url=https://web.archive.org/web/20210507013607/https://www.searchenginejournal.com/mozilla-firefox-internet-browser-market-share-gains-to-74/1082/ | url-status=live }} This meant that [[JScript]] became the de facto standard for [[client-side scripting]] on the Web. [68] => [69] => Microsoft initially participated in the standards process and implemented some proposals in its JScript language, but eventually it stopped collaborating on ECMA work. Thus ECMAScript 4 was mothballed. [70] => [71] => ===Growth and standardization=== [72] => During the period of [[Internet Explorer]] dominance in the early 2000s, client-side scripting was stagnant. This started to change in 2004, when the successor of Netscape, [[Mozilla]], released the [[Firefox]] browser. Firefox was well received by many, taking significant market share from Internet Explorer.{{cite news |url=https://news.bbc.co.uk/2/hi/business/4508897.stm |title=The assault on software giant Microsoft |last=Weber |first=Tim |date=May 9, 2005 |work=[[BBC News]] |archive-url=https://web.archive.org/web/20170925233936/https://news.bbc.co.uk/2/hi/business/4508897.stm |archive-date=September 25, 2017}} [73] => [74] => In 2005, Mozilla joined ECMA International, and work started on the [[ECMAScript for XML]] (E4X) standard. This led to Mozilla working jointly with [[Macromedia]] (later acquired by [[Adobe Systems]]), who were implementing E4X in their ActionScript 3 language, which was based on an ECMAScript 4 draft. The goal became standardizing ActionScript 3 as the new ECMAScript 4. To this end, Adobe Systems released the [[Tamarin (software)|Tamarin]] implementation as an [[Open-source model|open source]] project. However, Tamarin and ActionScript 3 were too different from established client-side scripting, and without cooperation from [[Microsoft]], ECMAScript 4 never reached fruition. [75] => [76] => Meanwhile, very important developments were occurring in open-source communities not affiliated with ECMA work. In 2005, [[Jesse James Garrett]] released a white paper in which he coined the term [[Ajax (programming)|Ajax]] and described a set of technologies, of which JavaScript was the backbone, to create [[web application]]s where data can be loaded in the background, avoiding the need for full page reloads. This sparked a renaissance period of JavaScript, spearheaded by open-source libraries and the communities that formed around them. Many new libraries were created, including [[jQuery]], [[Prototype JavaScript Framework|Prototype]], [[Dojo Toolkit]], and [[MooTools]]. [77] => [78] => [[Google]] debuted its [[Google Chrome|Chrome]] browser in 2008, with the [[V8 (JavaScript engine)|V8]] JavaScript engine that was faster than its competition.{{cite web|url=https://www.pcgameshardware.com/aid,687738/Big-browser-comparison-test-Internet-Explorer-vs-Firefox-Opera-Safari-and-Chrome-Update-Firefox-35-Final/Practice/|title=Big browser comparison test: Internet Explorer vs. Firefox, Opera, Safari and Chrome|work=PC Games Hardware|date=3 July 2009|publisher=Computec Media AG|access-date=June 28, 2010|archive-date=May 2, 2012|archive-url=https://web.archive.org/web/20120502043027/http://www.pcgameshardware.com/aid,687738/Big-browser-comparison-test-Internet-Explorer-vs-Firefox-Opera-Safari-and-Chrome-Update-Firefox-35-Final/Practice/|url-status=live}}{{cite web | url=https://lifehacker.com/lifehacker-speed-tests-safari-4-chrome-2-and-more-5286869 | title=Lifehacker Speed Tests: Safari 4, Chrome 2 | first=Kevin | last=Purdy | work=[[Lifehacker]] | date=June 11, 2009 | access-date=May 8, 2021 | archive-date=April 14, 2021 | archive-url=https://web.archive.org/web/20210414095403/https://lifehacker.com/lifehacker-speed-tests-safari-4-chrome-2-and-more-5286869 | url-status=live }} The key innovation was [[just-in-time compilation]] (JIT),{{cite web|url=https://brendaneich.com/2008/08/tracemonkey-javascript-lightspeed/|title=TraceMonkey: JavaScript Lightspeed, Brendan Eich's Blog|access-date=July 22, 2020|archive-date=December 4, 2015|archive-url=https://web.archive.org/web/20151204091540/https://brendaneich.com/2008/08/tracemonkey-javascript-lightspeed/|url-status=live}} so other browser vendors needed to overhaul their engines for JIT.{{cite magazine |title=Mozilla asks, 'Are we fast yet?' |url=https://www.wired.com/2010/09/mozilla-asks-are-we-fast-yet/ |magazine=Wired |access-date=January 18, 2019 |archive-date=June 22, 2018 |archive-url=https://web.archive.org/web/20180622213244/https://www.wired.com/2010/09/mozilla-asks-are-we-fast-yet/ |url-status=live }} [79] => [80] => In July 2008, these disparate parties came together for a conference in [[Oslo]]. This led to the eventual agreement in early 2009 to combine all relevant work and drive the language forward. The result was the ECMAScript 5 standard, released in December 2009. [81] => [82] => ===Reaching maturity=== [83] => Ambitious work on the language continued for several years, culminating in an extensive collection of additions and refinements being formalized with the publication of [[ECMAScript]] 6 in 2015.{{cite web |url=https://es6-features.org/ |title=ECMAScript 6: New Features: Overview and Comparison |website=es6-features.org |access-date=March 19, 2018 |archive-date=March 18, 2018 |archive-url=https://web.archive.org/web/20180318064130/https://es6-features.org/ |url-status=live }} [84] => [85] => The creation of [[Node.js]] in 2009 by [[Ryan Dahl]] sparked a significant increase in the usage of JavaScript outside of web browsers. Node combines the [[V8 (JavaScript engine)|V8]] engine, an [[event loop]], and [[Input/output|I/O]] [[Application programming interface|APIs]], thereby providing a stand-alone JavaScript runtime system.[https://books.google.com/books?id=ZH6bpbcrlvYC&q=nodejs Professional Node.js: Building JavaScript Based Scalable Software] {{Webarchive|url=https://web.archive.org/web/20170324021220/https://books.google.com/books?id=ZH6bpbcrlvYC&printsec=frontcover&dq=nodejs&hl=en&sa=X#v=onepage&q=nodejs&f=false |date=2017-03-24 }}, John Wiley & Sons, 01-Oct-2012[https://books.google.com/books?id=KGt-FxUEj48C&dq=nodejs&pg=PT24 Sams Teach Yourself Node.js in 24 Hours] {{Webarchive|url=https://web.archive.org/web/20170323192039/https://books.google.com/books?id=KGt-FxUEj48C&pg=PT24&dq=nodejs&hl=en&sa=X#v=onepage&q=nodejs&f=false |date=2017-03-23 }}, Sams Publishing, 05-Sep-2012 As of 2018, Node had been used by millions of developers,{{cite web |last1=Lawton |first1=George |title=The secret history behind the success of npm and Node |url=https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/The-secret-history-behind-the-success-of-npm-and-Node |website=TheServerSide |access-date=2 August 2021 |date=19 July 2018 |archive-date=2 August 2021 |archive-url=https://web.archive.org/web/20210802165613/https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/The-secret-history-behind-the-success-of-npm-and-Node |url-status=live }} and [[npm (software)|npm]] had the most modules of any [[package manager]] in the world.{{cite web |last1=Brown |first1=Paul |title=State of the Union: npm |url=https://www.linux.com/news/state-union-npm/ |website=Linux.com |access-date=2 August 2021 |date=13 January 2017 |archive-date=2 August 2021 |archive-url=https://web.archive.org/web/20210802165614/https://www.linux.com/news/state-union-npm/ |url-status=live }} [86] => [87] => The ECMAScript draft specification is currently maintained openly on [[GitHub]], and editions are produced via regular annual snapshots.{{cite web |url=https://thenewstack.io/whats-new-es2016/ |title=JavaScript Standard Moves to Yearly Release Schedule; Here is What's New for ES16 |last=Branscombe |first=Mary |date=2016-05-04 |access-date=2021-01-15 |work=The New Stack |archive-date=2021-01-16 |archive-url=https://web.archive.org/web/20210116181757/https://thenewstack.io/whats-new-es2016/ |url-status=live }} Potential revisions to the language are vetted through a comprehensive proposal process.{{cite web|url=https://tc39.es/process-document/|title=The TC39 Process|publisher=Ecma International|work=tc39.es|access-date=2021-01-15|archive-date=2021-02-07|archive-url=https://web.archive.org/web/20210207105535/https://tc39.es/process-document/|url-status=live}}{{cite web |url=https://github.com/tc39/proposals/blob/master/README.md |title=ECMAScript proposals |access-date=2021-01-15 |publisher=TC39 |archive-date=2020-12-04 |archive-url=https://web.archive.org/web/20201204221147/https://github.com/tc39/proposals/blob/master/README.md |url-status=live }} Now, instead of edition numbers, developers check the status of upcoming features individually. [88] => [89] => The current JavaScript ecosystem has many [[List of JavaScript libraries|libraries]] and [[web framework|frameworks]], established programming practices, and substantial usage of JavaScript outside of web browsers. Plus, with the rise of [[single-page application]]s and other JavaScript-heavy websites, several [[source-to-source compiler|transpilers]] have been created to aid the development process. [90] => [91] => ==Trademark== [92] => "JavaScript" is a [[trademark]] of [[Oracle Corporation]] in the United States.{{cite web |date=1997-05-06 |title=U.S. Trademark Serial No. 75026640 |url=https://tsdr.uspto.gov/#caseNumber=75026640&caseType=SERIAL_NO&searchType=statusSearch |url-status=live |archive-url=https://web.archive.org/web/20210713022850/https://tsdr.uspto.gov/#caseNumber=75026640&caseType=SERIAL_NO&searchType=statusSearch |archive-date=2021-07-13 |access-date=2021-05-08 |website=uspto.gov |publisher=[[United States Patent and Trademark Office]]}}{{cite web |title=Legal Notices |url=https://www.oracle.com/legal/trademarks.html |url-status=live |archive-url=https://web.archive.org/web/20210605142505/https://www.oracle.com/legal/trademarks.html |archive-date=2021-06-05 |access-date=2021-05-08 |website=oracle.com |publisher=[[Oracle Corporation]]}} The trademark was originally issued to [[Sun Microsystems]] on 6 May 1997, and was transferred to Oracle when they acquired Sun in 2009.{{Cite news |title=Oracle to buy Sun in $7.4-bn deal | newspaper=The Economic Times |url=https://economictimes.indiatimes.com/tech/software/oracle-to-buy-sun-in-7-4-bn-deal/articleshow/4427747.cms | date = 21 April 2009}} [93] => [94] => == Website client-side usage == [95] => JavaScript is the dominant [[client-side]] [[scripting language]] of the Web, with 99% of all [[website]]s using it for this purpose. Scripts are embedded in or included from [[HTML]] documents and interact with the [[Document Object Model|DOM]]. [96] => [97] => All major [[web browser]]s have a built-in [[JavaScript engine]] that executes the [[Source code|code]] on the user's device. [98] => [99] => ===Examples of scripted behavior=== [100] => * Loading new [[web page]] content without reloading the page, via [[Ajax (programming)|Ajax]] or a [[WebSocket]]. For example, [[user (computing)|user]]s of [[social media]] can send and receive messages without leaving the current page. [101] => * Web page animations, such as fading objects in and out, resizing, and moving them. [102] => * Playing [[browser game]]s. [103] => * Controlling the [[Media player software|playback]] of [[streaming media]]. [104] => * Generating [[pop-up ad]]s or alert boxes. [105] => * [[Data validation|Validating]] input values of a [[Form (HTML)|web form]] before the data is sent to a [[web server]]. [106] => * Logging data about the user's behavior then sending it to a server. The website owner can use this data for [[Web analytics|analytics]], [[ad tracking]], and [[personalization]]. [107] => *Redirecting a user to another page. [108] => * Storing and retrieving data on the user's device, via the [[web storage|storage]] or [[Indexed Database API|IndexedDB]] standards. [109] => [110] => === Libraries and frameworks=== [111] => Over 80% of websites use a third-party JavaScript [[Library (computing)|library]] or [[web framework]] as part of their client-side scripting.{{cite web|url=https://w3techs.com/technologies/overview/javascript_library|title=Usage statistics of JavaScript libraries for websites|website=W3Techs|access-date=2021-04-09}} [112] => [113] => [[jQuery]] is by far the most-used. Other notable ones include [[Angular (web framework)|Angular]], [[Bootstrap (front-end framework)|Bootstrap]], [[Lodash]], [[Modernizr]], [[React (software)|React]], [[Underscore.js|Underscore]], and [[Vue.js|Vue]]. Multiple options can be used in conjunction, such as jQuery and Bootstrap.{{cite web |title=Using jQuery with Bootstrap |url=https://clouddevs.com/jquery/web-projects-with-bootstrap/ |website=clouddevs.com |access-date=17 March 2024}} [114] => [115] => However, the term "Vanilla JS" was coined for websites not using any libraries or frameworks at all, instead relying entirely on standard JavaScript functionality.{{cite web |date=2020-06-16 |title=Vanilla JS |url=https://vanilla-js.com/ |url-status=live |archive-url=https://web.archive.org/web/20200616052335/https://vanilla-js.com/ |archive-date=June 16, 2020 |access-date=June 17, 2020 |website=vanilla-js.com}} [116] => [117] => ==Other usage{{anchor|Server-side_JavaScript|Uses_outside_web_pages}}== [118] => The use of JavaScript has expanded beyond its [[web browser]] roots. [[JavaScript engine]]s are now embedded in a variety of other software systems, both for [[server-side]] website deployments and non-browser [[application software|applications]]. [119] => [120] => Initial attempts at promoting server-side JavaScript usage were [[Netscape Enterprise Server]] and [[Microsoft]]'s [[Internet Information Services]],{{cite web |date=December 11, 1998 |title=Server-Side JavaScript Guide |url=https://docs.oracle.com/cd/E19957-01/816-6411-10/contents.htm |url-status=live |archive-url=https://web.archive.org/web/20210311173120/https://docs.oracle.com/cd/E19957-01/816-6411-10/contents.htm |archive-date=March 11, 2021 |access-date=May 8, 2021 |website=oracle.com |publisher=[[Oracle Corporation]]}}{{cite web|last1=Clinick|first1=Andrew|title=Introducing JScript .NET|url=https://msdn.microsoft.com/en-us/library/ms974588.aspx|website=Microsoft Developer Network|publisher=Microsoft|access-date=April 10, 2018|date=July 14, 2000|quote=[S]ince the 1996 introduction of JScript version 1.0 ... we've been seeing a steady increase in the usage of JScript on the server—particularly in Active Server Pages (ASP)|archive-date=November 10, 2017|archive-url=https://web.archive.org/web/20171110201649/https://msdn.microsoft.com/en-us/library/ms974588.aspx|url-status=live}} but they were small niches. Server-side usage eventually started to grow in the late 2000s, with the creation of [[Node.js]] and [[List of server-side JavaScript implementations|other approaches]].{{cite web |url=https://readwrite.com/2009/12/17/server-side_javascript_back_with_a_vengeance/ |title=Server-Side JavaScript, Back with a Vengeance |date=December 17, 2009 |website=readwrite.com |access-date=July 16, 2016 |author=Mahemoff, Michael |archive-date=June 17, 2016 |archive-url=https://web.archive.org/web/20160617030219/https://readwrite.com/2009/12/17/server-side_javascript_back_with_a_vengeance/ |url-status=live }} [121] => [122] => [[Electron (software framework)|Electron]], [[Apache Cordova|Cordova]], [[React Native]], and other [[application framework]]s have been used to create many applications with behavior implemented in JavaScript. Other non-browser applications include [[Adobe Acrobat]] support for scripting [[PDF]] documents{{cite web |date=2009-08-07 |title=JavaScript for Acrobat |url=https://www.adobe.com/devnet/acrobat/javascript.html |url-status=live |archive-url=https://web.archive.org/web/20090807065130/https://www.adobe.com/devnet/acrobat/javascript.html |archive-date=August 7, 2009 |access-date=August 18, 2009 |website=adobe.com}} and [[GNOME Shell]] extensions written in JavaScript.{{cite web |last=treitter |date=2013-02-02 |title=Answering the question: "How do I develop an app for GNOME?" |url=https://treitter.livejournal.com/14871.html |url-status=live |archive-url=https://web.archive.org/web/20130211032900/https://treitter.livejournal.com/14871.html |archive-date=2013-02-11 |access-date=2013-02-07 |website=livejournal.com}} [123] => [124] => JavaScript has recently begun to appear in some [[embedded system]]s, usually by leveraging Node.js.{{cite web |title=Tessel 2... Leverage all the libraries of Node.JS to create useful devices in minutes with Tessel. |url=https://tessel.io/ |url-status=live |archive-url=https://web.archive.org/web/20210526212559/https://tessel.io/ |archive-date=2021-05-26 |access-date=2021-05-08 |website=tessel.io}}{{cite web |title=Node.js Raspberry Pi GPIO Introduction |url=https://www.w3schools.com/nodejs/nodejs_raspberrypi_gpio_intro.asp |url-status=live |archive-url=https://web.archive.org/web/20210813192938/https://www.w3schools.com/nodejs/nodejs_raspberrypi_gpio_intro.asp |archive-date=2021-08-13 |access-date=2020-05-03 |website=w3schools.com}}{{cite web |title=Espruino – JavaScript for Microcontrollers |url=https://www.espruino.com/ |url-status=live |archive-url=https://web.archive.org/web/20200501010722/https://www.espruino.com/ |archive-date=2020-05-01 |access-date=2020-05-03 |website=espruino.com}} [125] => [126] => == Execution == [127] => ===JavaScript engine=== [128] => {{Excerpt|JavaScript engine}} [129] => [130] => === Runtime system === [131] => The JavaScript engine must be embedded within a [[runtime system]] (either a [[web browser]] or a standalone system) to provide objects and methods by which scripts can interact with the larger environment. This includes the necessary APIs for [[input/output|I/O]], such as [[computer network|networking]], [[data storage|storage]], or [[computer graphics|graphics]] facilities. The runtime also provides the ability to import scripts. [132] => [133] => JavaScript is a single-[[Thread (computing)|threaded]] language. The runtime processes [[Message (computer science)|messages]] from a [[Queue (abstract data type)|queue]] one at a time, and it calls a [[Subroutine|function]] associated with each new message, creating a [[call stack]] frame with the function's [[Parameter (computer programming)|arguments]] and [[local variable]]s. The call stack shrinks and grows based on the function's needs. When the call stack is empty upon function completion, JavaScript proceeds to the next message in the queue. This is called the [[event loop]], described as "run to completion" because each message is fully processed before the next message is considered. However, the language's [[Concurrency (computer science)|concurrency model]] describes the event loop as [[Asynchronous I/O|non-blocking]]: program I/O is performed using [[Event (computing)|events]] and [[Callback (computer programming)|callback functions]]. This means, for example, that JavaScript can process a mouse click while waiting for a database query to return information.{{cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop|title=Concurrency model and Event Loop|website=Mozilla Developer Network|access-date=August 28, 2015|archive-date=September 5, 2015|archive-url=https://web.archive.org/web/20150905045241/https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop|url-status=live}} [134] => [135] => The notable standalone runtimes are [[Node.js]], [[Deno (software)|Deno]], and [[Bun (software)|Bun]]. [136] => [137] => ==Features== [138] => The following features are common to all conforming ECMAScript implementations unless explicitly specified otherwise. [139] => [140] => ===Imperative and structured=== [141] => {{Main|Structured programming}} [142] => [143] => JavaScript supports much of the [[structured programming]] syntax from [[C (computer language)|C]] (e.g., if statements, while loops, switch statements, do while loops, etc.). One partial exception is [[scope (computer science)|scoping]]: originally JavaScript only had [[function scoping]] with var; [[block scoping]] was added in ECMAScript 2015 with the keywords let and [[const (computer programming)|const]]. 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.{{cite book|last=Flanagan|first=David|title=JavaScript: The Definitive Guide: 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}} [144] => [145] => ===Weakly typed=== [146] => {{Main|Weakly typed}} [147] => [148] => JavaScript is [[Strong and weak typing|weakly typed]], which means certain types are implicitly cast depending on the operation used.{{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}} [149] => [150] => * The binary + operator casts both operands to a string unless both operands are numbers. This is because the addition operator doubles as a concatenation operator [151] => * The binary - operator always casts both operands to a number [152] => * Both unary operators (+, -) always cast the operand to a number [153] => [154] => Values are cast to strings like the following: [155] => [156] => * Strings are left as-is [157] => * Numbers are converted to their string representation [158] => * Arrays have their elements cast to strings after which they are joined by commas (,) [159] => * Other objects are converted to the string [object Object] where Object is the name of the constructor of the object [160] => [161] => Values are cast to numbers by casting to strings and then casting the strings to numbers. These processes can be modified by defining toString and valueOf functions on the [[#Object-orientation (prototype-based)|prototype]] for string and number casting respectively. [162] => [163] => JavaScript has received criticism for the way it implements these conversions as the complexity of the rules can be mistaken for inconsistency.{{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 }} 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. [164] => [165] => {| class="wikitable" [166] => |+JavaScript type conversions [167] => !left operand [168] => !operator [169] => !right operand [170] => !result [171] => |- [172] => |[] (empty array) [173] => |+ [174] => |[] (empty array) [175] => |"" (empty string) [176] => |- [177] => |[] (empty array) [178] => |+ [179] => |{} (empty object) [180] => |"[object Object]" (string) [181] => |- [182] => |false (boolean) [183] => |+ [184] => |[] (empty array) [185] => |"false" (string) [186] => |- [187] => |"123"(string) [188] => |+ [189] => |1 (number) [190] => |"1231" (string) [191] => |- [192] => |"123" (string) [193] => |- [194] => |1 (number) [195] => |122 (number) [196] => |- [197] => |"123" (string) [198] => |- [199] => |"abc" (string) [200] => |[[NaN]] (number) [201] => |} [202] => [203] => Often also mentioned is {} + [] resulting in 0 (number). This is misleading: the {} 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 + operator. If the expression is wrapped in parentheses - ({} + []) - the curly brackets are interpreted as an empty object and the result of the expression is "[object Object]" as expected. [204] => [205] => ===Dynamic=== [206] => {{Main|Dynamic Programming}} [207] => [208] => ==== Typing ==== [209] => {{Main|Dynamic typing}} [210] => [211] => 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]].{{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}} JavaScript supports various ways to test the type of objects, including [[duck typing]].{{Sfn|Flanagan|2006|pp=176–178}} [212] => [213] => ==== Run-time evaluation ==== [214] => {{Main|eval}} [215] => JavaScript includes an [[eval]] function that can execute statements provided as strings at run-time. [216] => [217] => ===Object-orientation (prototype-based)=== [218] => Prototypal inheritance in JavaScript is described by [[Douglas Crockford]] as: [219] => {{Blockquote [220] => |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?{{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}} [221] => }} [222] => [223] => 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 (obj.x = 10) and bracket notation (obj['x'] = 10). 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 for...in loop. [224] => [225] => ==== Prototypes ==== [226] => {{Main|Prototype-based programming}} [227] => [228] => JavaScript uses [[prototype-based programming|prototypes]] where many other object-oriented languages use [[Class (computer science)|classes]] for [[Inheritance (object-oriented programming)|inheritance]].{{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}} It is possible to simulate many class-based features with prototypes in JavaScript.{{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 }} [229] => [230] => ==== Functions as object constructors ==== [231] => [232] => 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 Object prototype).{{cite book|last=Haverbeke|first=Marijn|title=Eloquent JavaScript|year=2011|publisher=No Starch Press|isbn=978-1-59327-282-1|pages=95–97 |url=https://books.google.com/books?id=9U5I_tskq9MC&pg=PA95 }} ECMAScript 5 offers the Object.create method, allowing explicit creation of an instance without automatically inheriting from the Object prototype (older environments can assign the prototype to null).{{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}} The constructor's prototype 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. JavaScript's built-in constructors, such as Array or Object, also have prototypes that can be modified. While it is possible to modify the Object prototype, it is generally considered bad practice because most objects in JavaScript will inherit methods and properties from the Object prototype, and they may not expect the prototype to be modified.{{cite book|last=Herman|first=David|title=Effective JavaScript|year=2013|publisher=Addison-Wesley|isbn=978-0-321-81218-6|pages=125–127 |url=https://books.google.com/books?id=Nz9iAwAAQBAJ&pg=PA125 }} [233] => [234] => ==== Functions as methods ==== [235] => {{Main|Method (computer science)}} [236] => [237] => [238] => 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. [239] => [240] => ===Functional=== [241] => {{Main|Functional programming}} [242] => [243] => JavaScript [[Subroutine|function]]s are [[first-class function|first-class]]; a function is considered to be an object.{{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}} As such, a function may have properties and methods, such as .call() and .bind().{{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 }} [244] => [245] => ==== Lexical closure ==== [246] => {{Main|Closure (computer programming)}} [247] => [248] => A ''nested'' function is a function defined within another function. It is created each time the outer function is invoked. [249] => [250] => 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}} [251] => [252] => ==== Anonymous function ==== [253] => {{Main|Anonymous function}} [254] => [255] => JavaScript also supports [[anonymous function]]s. [256] => [257] => ===Delegative=== [258] => {{Main|Delegation (object-oriented programming)}} [259] => JavaScript supports implicit and explicit [[Delegation (object-oriented programming)|delegation]]. [260] => [261] => ==== Functions as roles (Traits and Mixins) ==== [262] => {{Main|Role-oriented programming|Traits (computer science)|Mixin}} [263] => [264] => JavaScript natively supports various function-based implementations of [[Role-oriented programming|Role]][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.blogpsot.de, April 11, 2014. patterns like [[Traits (computer science)|Traits]][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.{{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 }} and [[Mixin]]s.{{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… }} Such a function defines additional behavior by at least one method bound to the this keyword within its function body. A Role then has to be delegated explicitly via call or apply to objects that need to feature additional behavior that is not shared via the prototype chain. [265] => [266] => ==== Object composition and inheritance ==== [267] => 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. [268] => [269] => ===Miscellaneous=== [270] => ==== Zero-based numbering ==== [271] => JavaScript is a [[Zero-based numbering#Usage in programming languages|zero-index]] language. [272] => [273] => ==== Variadic functions ==== [274] => {{Main|Variadic function}} [275] => [276] => [277] => 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 arguments object. [[Variadic functions]] can also be created by using the [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind bind] method. [278] => [279] => ==== Array and object literals ==== [280] => {{Main|Associative arrays|Object literal}} [281] => [282] => 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. [283] => [284] => ==== Regular expressions ==== [285] => {{Main|Regular expression}} [286] => [287] => In a manner similar to [[Perl]], JavaScript also supports [[regular expression]]s, which provide a concise and powerful syntax for text manipulation that is more sophisticated than the built-in string functions.{{cite book | last=Haverbeke | first=Marijn | title=Eloquent JavaScript | year=2011 | publisher=No Starch Press|isbn=978-1-59327-282-1|pages=139–149 |url=https://books.google.com/books?id=9U5I_tskq9MC&pg=PA139 }} [288] => [289] => ==== Promises and Async/await ==== [290] => JavaScript supports [[futures and promises|promises]] and [[Async/await]] for handling asynchronous operations.{{cn|date=August 2023}} [291] => [292] => ===== Promises ===== [293] => {{Main|Futures and promises}} [294] => [295] => A built-in Promise object provides functionality for handling promises and associating handlers with an asynchronous action's eventual result. Recently, the JavaScript specification introduced 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. [296] => [297] => ===== Async/await ===== [298] => {{Main|Async/await}} [299] => [300] => 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. [301] => [302] => ===Vendor-specific extensions=== [303] => Historically, some [[JavaScript engine]]s supported these non-standard features: [304] => * conditional catch clauses (like Java) [305] => * [[List comprehension|array comprehensions]] and generator expressions (like Python) [306] => * concise function expressions (function(args) expr; this experimental syntax predated arrow functions) [307] => * [[ECMAScript for XML]] (E4X), an extension that adds native XML support to ECMAScript (unsupported in Firefox since version 21{{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}}) [308] => [309] => ==Syntax== [310] => {{Main|JavaScript syntax}} [311] => [312] => ===Simple examples=== [313] => [[Variable (computer science)|Variables]] in JavaScript can be defined using either the var,{{cite web | url=https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var | title=var – JavaScript | publisher=The [[Mozilla Developer Network]] | access-date=December 22, 2012 | archive-date=December 23, 2012 | archive-url=https://web.archive.org/web/20121223162713/https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var | url-status=live }} let{{cite web |title=let |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let |website=MDN web docs |publisher=Mozilla |access-date=June 27, 2018 |ref=moz_let |archive-date=May 28, 2019 |archive-url=https://web.archive.org/web/20190528140803/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let |url-status=live }} or const{{cite web |title=const |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const |website=MDN web docs |publisher=Mozilla |access-date=June 27, 2018 |ref=moz_const |archive-date=June 28, 2018 |archive-url=https://web.archive.org/web/20180628044054/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const |url-status=live }} keywords. Variables defined without keywords will be defined at the global scope. [314] => [315] => [316] => // Declares a function-scoped variable named `x`, and implicitly assigns the [317] => // special value `undefined` to it. Variables without value are automatically [318] => // set to undefined. [319] => // var is generally considered bad practice and let and const are usually preferred. [320] => var x; [321] => [322] => // Variables can be manually set to `undefined` like so [323] => let x2 = undefined; [324] => [325] => // Declares a block-scoped variable named `y`, and implicitly sets it to [326] => // `undefined`. The `let` keyword was introduced in ECMAScript 2015. [327] => let y; [328] => [329] => // Declares a block-scoped, un-reassignable variable named `z`, and sets it to [330] => // a string literal. The `const` keyword was also introduced in ECMAScript 2015, [331] => // and must be explicitly assigned to. [332] => [333] => // The keyword `const` means constant, hence the variable cannot be reassigned [334] => // as the value is `constant`. [335] => const z = "this value cannot be reassigned!"; [336] => [337] => // Declares a global-scoped variable and assigns 3. This is generally considered [338] => // bad practice, and will not work if strict mode is on. [339] => t = 3; [340] => [341] => // Declares a variable named `myNumber`, and assigns a number literal (the value [342] => // `2`) to it. [343] => let myNumber = 2; [344] => [345] => // Reassigns `myNumber`, setting it to a string literal (the value `"foo"`). [346] => // JavaScript is a dynamically-typed language, so this is legal. [347] => myNumber = "foo"; [348] => [349] => [350] => Note the [[Comment (computer programming)|comments]] in the examples above, all of which were preceded with two [[Slash (punctuation)|forward slashes]]. [351] => [352] => There is no built-in [[Input/output]] functionality in JavaScript, instead it is provided by the run-time environment. The ECMAScript specification in edition 5.1 mentions that "there are no provisions in this specification for input of external data or output of computed results".{{cite web| url=https://www.ecma-international.org/ecma-262/5.1/#sec-4| title=ECMAScript Language Specification – ECMA-262 Edition 5.1| publisher=[[Ecma International]]| access-date=December 22, 2012| archive-date=November 26, 2012| archive-url=https://web.archive.org/web/20121126044218/https://ecma-international.org/ecma-262/5.1/#sec-4| url-status=live}} [353] => However, most runtime environments have a console object that can be used to print output.{{cite web|title=console|url=https://developer.mozilla.org/en-US/docs/DOM/console|work=Mozilla Developer Network|publisher=[[Mozilla]]|access-date=April 6, 2013|archive-date=February 28, 2013|archive-url=https://web.archive.org/web/20130228112150/https://developer.mozilla.org/en-US/docs/DOM/console|url-status=live}} Here is a minimalist [["Hello, World!" program]] in JavaScript in a runtime environment with a console object: [354] => [355] => [356] => console.log("Hello, World!"); [357] => [358] => In HTML documents, a program like this is required for an output: [359] => [360] => // Text nodes can be made using the "write" method. [361] => // This is frowned upon, as it can overwrite the document if the document is fully loaded. [362] => document.write('foo'); [363] => [364] => // Elements can be made too. First, they have to be created in the DOM. [365] => const myElem = document.createElement('span'); [366] => [367] => // Attributes like classes and the id can be set as well [368] => myElem.classList.add('foo'); [369] => myElem.id = 'bar'; [370] => [371] => // After setting this, the tag will look like this: `` [372] => myElem.setAttribute('data-attr', 'baz'); // Which could also be written as `myElem.dataset.attr = 'baz'` [373] => [374] => // Finally append it as a child element to the in the HTML [375] => document.body.appendChild(myElem); [376] => [377] => // Elements can be imperatively grabbed with querySelector for one element, or querySelectorAll for multiple elements that can be looped with forEach [378] => document.querySelector('.class'); // Selects the first element with the "class" class [379] => document.querySelector('#id'); // Selects the first element with an `id` of "id" [380] => document.querySelector('[data-other]'); // Selects the first element with the "data-other" attribute [381] => document.querySelectorAll('.multiple'); // Returns an Array-like NodeList of all elements with the "multiple" class [382] => A simple [[Recursion (computer science)|recursive]] function to calculate the [[factorial]] of a [[natural number]]: [383] => [384] => [385] => function factorial(n) { [386] => // Checking the argument for legitimacy. Factorial is defined for positive integers. [387] => if (isNaN(n)) { [388] => console.error("Non-numerical argument not allowed."); [389] => return NaN; // The special value: Not a Number [390] => } [391] => if (n === 0) [392] => return 1; // 0! = 1 [393] => if (n < 0) [394] => return undefined; // Factorial of negative numbers is not defined. [395] => if (n % 1) { [396] => console.warn(`${n} will be rounded to the closest integer. For non-integers consider using gamma function instead.`); [397] => n = Math.round(n); [398] => } [399] => // The above checks need not be repeated in the recursion, hence defining the actual recursive part separately below. [400] => [401] => // The following line is a function expression to recursively compute the factorial. It uses the arrow syntax introduced in ES6. [402] => const recursivelyCompute = a => a > 1 ? a * recursivelyCompute(a - 1) : 1; // Note the use of the ternary operator `?`. [403] => return recursivelyCompute(n); [404] => } [405] => [406] => factorial(3); // Returns 6 [407] => [408] => [409] => An [[anonymous function]] (or lambda): [410] => [411] => [412] => const counter = function() { [413] => let count = 0; [414] => return function() { [415] => return ++count; [416] => } [417] => }; [418] => [419] => const x = counter(); [420] => x(); // Returns 1 [421] => x(); // Returns 2 [422] => x(); // Returns 3 [423] => [424] => [425] => This example shows that, in JavaScript, [[Closure (computer programming)|function closures]] capture their non-local variables by reference. [426] => [427] => Arrow functions were first introduced in [[ECMAScript#6th Edition – ECMAScript 2015|6th Edition - ECMAScript 2015]]. They shorten the syntax for writing functions in JavaScript. Arrow functions are anonymous, so a variable is needed to refer to them in order to invoke them after their creation, unless surrounded by parenthesis and executed immediately. [428] => [429] => Example of arrow function: [430] => [431] => [432] => // Arrow functions let us omit the `function` keyword. [433] => // Here `long_example` points to an anonymous function value. [434] => const long_example = (input1, input2) => { [435] => console.log("Hello, World!"); [436] => const output = input1 + input2; [437] => [438] => return output; [439] => }; [440] => [441] => // If there are no braces, the arrow function simply returns the expression [442] => // So here it's (input1 + input2) [443] => const short_example = (input1, input2) => input1 + input2; [444] => [445] => long_example(2, 3); // Prints "Hello, World!" and returns 5 [446] => short_example(2, 5); // Returns 7 [447] => [448] => // If an arrow function has only one parameter, the parentheses can be removed. [449] => const no_parentheses = input => input + 2; [450] => [451] => no_parentheses(3); // Returns 5 [452] => [453] => // An arrow function, like other function definitions, can be executed in the same statement as they are created. [454] => // This is useful when writing libraries to avoid filling the global scope, and for closures. [455] => let three = ((a, b) => a + b) (1, 2); [456] => [457] => const generate_multiplier_function = a => (b => isNaN(b) || !b ? a : a*=b); [458] => const five_multiples = generate_multiplier_function(5); // The supplied argument "seeds" the expression and is retained by a. [459] => five_multiples(1); // Returns 5 [460] => five_multiples(3); // Returns 15 [461] => five_multiples(4); // Returns 60 [462] => [463] => [464] => In JavaScript, [[Object (computer science)|objects]] can be created as [[Instance (computer science)|instances]] of a [[class (computer science)|class]]. [465] => [466] => Object class example: [467] => [468] => class Ball { [469] => [470] => constructor(radius) { [471] => this.radius = radius; [472] => this.area = Math.PI * ( radius ** 2 ); [473] => } [474] => [475] => // Classes (and thus objects) can contain functions known as methods [476] => show() { [477] => console.log(this.radius); [478] => } [479] => }; [480] => [481] => const myBall = new Ball(5); // Creates a new instance of the ball object with radius 5 [482] => myBall.radius++; // Object properties can usually be modified from the outside [483] => myBall.show(); // Using the inherited "show" function logs "6" [484] => [485] => [486] => In JavaScript, [[Object (computer science)|objects]] can be instantiated directly from a function. [487] => [488] => Object functional example: [489] => [490] => function Ball(radius) { [491] => [492] => const area = Math.PI * ( radius ** 2 ); [493] => const obj = { radius, area }; [494] => [495] => // Objects are mutable, and functions can be added as properties. [496] => obj.show = () => console.log(obj.radius); [497] => return obj; [498] => }; [499] => [500] => const myBall = Ball(5); // Creates a new ball object with radius 5. No "new" keyword needed. [501] => myBall.radius++; // The instance property can be modified. [502] => myBall.show(); // Using the "show" function logs "6" - the new instance value. [503] => [504] => [505] => [[Variadic function]] demonstration (arguments is a special [[variable (programming)|variable]]):{{cite web|title=arguments|url=https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments|work=Mozilla Developer Network|publisher=[[Mozilla]]|access-date=April 6, 2013|archive-date=April 13, 2013|archive-url=https://web.archive.org/web/20130413230225/https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments|url-status=live}} [506] => [507] => [508] => function sum() { [509] => let x = 0; [510] => [511] => for (let i = 0; i < arguments.length; ++i) [512] => x += arguments[i]; [513] => [514] => return x; [515] => } [516] => [517] => sum(1, 2); // Returns 3 [518] => sum(1, 2, 3); // Returns 6 [519] => [520] => // As of ES6, using the rest operator. [521] => function sum(...args) { [522] => return args.reduce((a, b) => a + b); [523] => } [524] => [525] => sum(1, 2); // Returns 3 [526] => sum(1, 2, 3); // Returns 6 [527] => [528] => [529] => [[Immediately-invoked function expression]]s are often used to create closures. Closures allow gathering properties and methods in a namespace and making some of them private: [530] => [531] => [532] => let counter = (function() { [533] => let i = 0; // Private property [534] => [535] => return { // Public methods [536] => get: function() { [537] => alert(i); [538] => }, [539] => set: function(value) { [540] => i = value; [541] => }, [542] => increment: function() { [543] => alert(++i); [544] => } [545] => }; [546] => })(); // Module [547] => [548] => counter.get(); // Returns 0 [549] => counter.set(6); [550] => counter.increment(); // Returns 7 [551] => counter.increment(); // Returns 8 [552] => [553] => [554] => [[Generator (computer programming)|Generator]] objects (in the form of generator functions) provide a function which can be called, exited, and re-entered while maintaining internal context (statefulness).{{Cite web |title=function* - JavaScript {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* |access-date=2022-09-27 |website=developer.mozilla.org |language=en-US}} [555] => function* rawCounter() { [556] => yield 1; [557] => yield 2; [558] => } [559] => [560] => function* dynamicCounter() { [561] => let count = 0; [562] => while (true) { [563] => // It is not recommended to utilize while true loops in most cases. [564] => yield ++count; [565] => } [566] => } [567] => [568] => // Instances [569] => const counter1 = rawCounter(); [570] => const counter2 = dynamicCounter(); [571] => [572] => // Implementation [573] => counter1.next(); // {value: 1, done: false} [574] => counter1.next(); // {value: 2, done: false} [575] => counter1.next(); // {value: undefined, done: true} [576] => [577] => counter2.next(); // {value: 1, done: false} [578] => counter2.next(); // {value: 2, done: false} [579] => counter2.next(); // {value: 3, done: false} [580] => // ...infinitely [581] => [582] => [583] => JavaScript can export and import from modules:{{cite web |title=JavaScript modules |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules |website=MDN Web Docs |publisher=Mozilla |access-date=28 July 2022 |archive-url=https://web.archive.org/web/20220717083604/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules |archive-date=17 July 2022 |url-status=live}} [584] => [585] => Export example: [586] => [587] => /* mymodule.js */ [588] => // This function remains private, as it is not exported [589] => let sum = (a, b) => { [590] => return a + b; [591] => } [592] => [593] => // Export variables [594] => export let name = 'Alice'; [595] => export let age = 23; [596] => [597] => // Export named functions [598] => export function add(num1, num2) { [599] => return num1 + num2; [600] => } [601] => [602] => // Export class [603] => export class Multiplication { [604] => constructor(num1, num2) { [605] => this.num1 = num1; [606] => this.num2 = num2; [607] => } [608] => [609] => add() { [610] => return sum(this.num1, this.num2); [611] => } [612] => } [613] => [614] => [615] => Import example: [616] => [617] => // Import one property [618] => import { add } from './mymodule.js'; [619] => console.log(add(1, 2)); [620] => //> 3 [621] => [622] => // Import multiple properties [623] => import { name, age } from './mymodule.js'; [624] => console.log(name, age); [625] => //> "Alice", 23 [626] => [627] => // Import all properties from a module [628] => import * from './module.js' [629] => console.log(name, age); [630] => //> "Alice", 23 [631] => console.log(add(1,2)); [632] => //> 3 [633] => [634] => [635] => ===More advanced example=== [636] => This sample code displays various JavaScript features. [637] => [638] => [639] => [640] => /* Finds the lowest common multiple (LCM) of two numbers */ [641] => function LCMCalculator(x, y) { // constructor function [642] => if (isNaN(x*y)) throw new TypeError("Non-numeric arguments not allowed."); [643] => const checkInt = function(x) { // inner function [644] => if (x % 1 !== 0) [645] => throw new TypeError(x + "is not an integer"); [646] => [647] => return x; [648] => }; [649] => [650] => this.a = checkInt(x) [651] => // semicolons ^^^^ are optional, a newline is enough [652] => this.b = checkInt(y); [653] => } [654] => // The prototype of object instances created by a constructor is [655] => // that constructor's "prototype" property. [656] => LCMCalculator.prototype = { // object literal [657] => constructor: LCMCalculator, // when reassigning a prototype, set the constructor property appropriately [658] => gcd: function() { // method that calculates the greatest common divisor [659] => // Euclidean algorithm: [660] => let a = Math.abs(this.a), b = Math.abs(this.b), t; [661] => [662] => if (a < b) { [663] => // swap variables [664] => // t = b; b = a; a = t; [665] => [a, b] = [b, a]; // swap using destructuring assignment (ES6) [666] => } [667] => [668] => while (b !== 0) { [669] => t = b; [670] => b = a % b; [671] => a = t; [672] => } [673] => [674] => // Only need to calculate GCD once, so "redefine" this method. [675] => // (Actually not redefinition—it's defined on the instance itself, [676] => // so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd. [677] => // Note that this leads to a wrong result if the LCMCalculator object members "a" or "b" are altered afterwards.) [678] => // Also, 'gcd' === "gcd", this['gcd'] === this.gcd [679] => this['gcd'] = function() { [680] => return a; [681] => }; [682] => [683] => return a; [684] => }, [685] => [686] => // Object property names can be specified by strings delimited by double (") or single (') quotes. [687] => "lcm": function() { [688] => // Variable names do not collide with object properties, e.g., |lcm| is not |this.lcm|. [689] => // not using |this.a*this.b| to avoid FP precision issues [690] => let lcm = this.a / this.gcd() * this.b; [691] => [692] => // Only need to calculate lcm once, so "redefine" this method. [693] => this.lcm = function() { [694] => return lcm; [695] => }; [696] => [697] => return lcm; [698] => }, [699] => [700] => // Methods can also be declared using ES6 syntax [701] => toString() { [702] => // Using both ES6 template literals and the (+) operator to concatenate values [703] => return `LCMCalculator: a = ${this.a}, b = ` + this.b; [704] => } [705] => }; [706] => [707] => // Define generic output function; this implementation only works for Web browsers [708] => function output(x) { [709] => document.body.appendChild(document.createTextNode(x)); [710] => document.body.appendChild(document.createElement('br')); [711] => } [712] => [713] => // Note: Array's map() and forEach() are defined in JavaScript 1.6. [714] => // They are used here to demonstrate JavaScript's inherent functional nature. [715] => [ [716] => [25, 55], [717] => [21, 56], [718] => [22, 58], [719] => [28, 56] [720] => ].map(function(pair) { // array literal + mapping function [721] => return new LCMCalculator(pair[0], pair[1]); [722] => }).sort((a, b) => a.lcm() - b.lcm()) // sort with this comparative function; => is a shorthand form of a function, called "arrow function" [723] => .forEach(printResult); [724] => [725] => function printResult(obj) { [726] => output(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm()); [727] => } [728] => [729] => [730] => The following output should be displayed in the browser window. [731] => [732] => LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56 [733] => LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168 [734] => LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275 [735] => LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638 [736] => [737] => [738] => ==Security== [739] => {{See also|Browser security}} [740] => JavaScript and the [[Document Object Model|DOM]] provide the potential for malicious authors to deliver scripts to run on a client computer via the Web. Browser authors minimize this risk using two restrictions. First, scripts run in a [[Sandbox (computer security)|sandbox]] in which they can only perform Web-related actions, not general-purpose programming tasks like creating files. Second, scripts are constrained by the [[same-origin policy]]: scripts from one website do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox. [741] => [742] => There are subsets of general JavaScript—ADsafe, Secure ECMAScript (SES)—that provide greater levels of security, especially on code created by third parties (such as advertisements).{{cite web | url=https://www.adsafe.org/ | title=Making JavaScript Safe for Advertising | publisher=ADsafe | access-date=2021-05-08 | archive-date=2021-07-06 | archive-url=https://web.archive.org/web/20210706153324/https://www.adsafe.org/ | url-status=live }}{{cite web | url=https://code.google.com/p/es-lab/wiki/SecureEcmaScript | title=Secure ECMA Script (SES) | access-date=May 26, 2013 | archive-date=May 15, 2013 | archive-url=https://web.archive.org/web/20130515073412/https://code.google.com/p/es-lab/wiki/SecureEcmaScript | url-status=live }} Closure Toolkit is another project for safe embedding and isolation of third-party JavaScript and HTML.{{cite web|title=Google Caja Project|url=https://developers.google.com/caja/|url-status=live|website=[[Google]]|access-date=2021-07-09|archive-date=2021-01-22|archive-url=https://web.archive.org/web/20210122083321/https://developers.google.com/caja/}} [743] => [744] => [[Content Security Policy]] is the main intended method of ensuring that only trusted code is executed on a Web page. [745] => [746] => ===Cross-site scripting=== [747] => {{Main|Cross-site scripting}} [748] => [749] => A common JavaScript-related security problem is [[cross-site scripting]] (XSS), a violation of the [[same-origin policy]]. XSS vulnerabilities occur when an attacker can cause a target Website, such as an online banking website, to include a malicious script in the webpage presented to a victim. The script in this example can then access the banking application with the privileges of the victim, potentially disclosing secret information or transferring money without the victim's authorization. One important solution to XSS vulnerabilities is [[HTML sanitization]]. [750] => [751] => Some browsers include partial protection against ''reflected'' XSS attacks, in which the attacker provides a URL including malicious script. However, even users of those browsers are vulnerable to other XSS attacks, such as those where the malicious code is stored in a database. Only correct design of Web applications on the server-side can fully prevent XSS. [752] => [753] => XSS vulnerabilities can also occur because of implementation mistakes by browser authors.{{cite web |url=https://www.mozillazine.org/talkback.html?article=4392 |title=Mozilla Cross-Site Scripting Vulnerability Reported and Fixed – MozillaZine Talkback |website=Mozillazine.org |access-date=February 24, 2017 |archive-date=July 21, 2011 |archive-url=https://web.archive.org/web/20110721230916/http://www.mozillazine.org/talkback.html?article=4392 |url-status=live }} [754] => [755] => ===Cross-site request forgery=== [756] => {{Main|Cross-site request forgery}} [757] => [758] => Another cross-site vulnerability is [[cross-site request forgery]] (CSRF). In CSRF, code on an attacker's site tricks the victim's browser into taking actions the user did not intend at a target site (like transferring money at a bank). When target sites rely solely on cookies for request authentication, requests originating from code on the attacker's site can carry the same valid login credentials of the initiating user. In general, the solution to CSRF is to require an authentication value in a hidden form field, and not only in the cookies, to authenticate any request that might have lasting effects. Checking the HTTP Referrer header can also help. [759] => [760] => "JavaScript hijacking" is a type of CSRF attack in which a