<<

Additional Resources 3 Easy Ways to Learn More and Stay Current

Programming Blog Read more news and analysis about JavaScript, HTML5, CSS3, and other technologies. programming.oreilly.com

Programming Get programming-related news and Newsletter content delivered weekly to your inbox. oreilly.com/code/newsletter.html

Fluent Conference Immerse yourself in learning at the annual O’Reilly Fluent Conference. Join developers, UX/UI designers, project teams, and a wide range of other people who work with web platform technologies to share experiences and expertise— and to learn what you need to know to stay competitive. fluentconf.com

©2014 O’Reilly Media, Inc. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. 14114 The Web Platform Building a Solid Stack of HTML, CSS, and JavaScript

Simon St.Laurent The Web Platform by Simon St.Laurent Copyright © 2014 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editor: Simon St.Laurent

January 2014: First Edition

Revision History for the First Edition: 2014-01-10: First release Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The Web Platform: Building a Solid Stack of HTML, CSS, and JavaScript and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their prod‐ ucts are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

ISBN: 978-1-491-95011-1 [LSI] Table of Contents

Preface...... v

HTML: Moving Beyond the Standard...... 1

The Power of Markup...... 5

CSS Selectors Have Superpowers...... 9

JavaScript: Not as Expected...... 13

From JavaScript to Declarative Markup...... 17

Toward Responsive Web Programming...... 19

Will JavaScript Take Over the Programming World?...... 21 Concentration: The Wrong Story 21 Dispersion: A More Likely Story? 24

iii

Preface

The Web keeps growing, expanding from a content distribution sys‐ tem to an application platform connecting people within organiza‐ tions and across the world. For the past 15 years, the Web’s core has proven remarkably stable. Even as developers create more technolo‐ gies and techniques, they still mostly use the core stack of HTML plus CSS and JavaScript, with a few extensions mostly provided through additional standards. Can that stack persist? Programmers have longed for alternatives for at least as long as the Web has existed, largely because web develop‐ ment doesn’t quite feel like programming. Creating documents, styling them, and then adding some program logic is pretty different from standard models of creating objects and logic to display something on a screen. The Web endures, though, largely because of its unique approach. Markup and simple hypertext offered a quick way to build and share documents across a network, but we have layered much more on top of those capabilities. Beyond simplicity—which isn’t especially prev‐ alent today—why do web tools work so well?

• Both HTML markup and CSS stylesheets are declarative, making browsers do work without requiring programming logic. • JavaScript layers well on top of HTML, especially after it learned the power of declarative selectors from CSS. • Separating content, presentation, and logic has made reuse much simpler.

v • The ubiquity of the Web combined with the competitive nature of browser vendors encourages major investment in rendering engines and JavaScript performance. • Even though web browsers are written by many different people with different motives, they’ve been able to work well enough to‐ gether to extend browser capabilities.

The best part, though, is that those foundations let us do new things. I hope you’ll find that web technologies continue to provide a solid base on which to build your dream projects!

These pieces were originally written for the O’Reil‐ ly Programming blog and then adjusted to better fit the times and the format. If you’d like to see more on similar topics, please explore http:// programming.oreilly.com.

vi | Preface HTML: Moving Beyond the Standard

You can create your own markup vocabularies without learning XML. You just need to figure out what markup you want to use, and then create CSS and JavaScript to tell the browser what to do with it. Cre‐ ating your own extensions to the HTML vocabulary lets you describe your content in the terms that make sense to you and can help you drastically reduce repetition and confusion. When HTML first appeared, it offered a coherent if limited vocabulary for sharing content on the newly created . Today, now that HTML has handed off most of its actual work to other specifica‐ tions, developers can start to choose their own markup vocabularies and processing. When the W3C first formed, it formed around HTML, the core stan‐ dard of content on the Web, defining the structure, appearance, and behavior of content. Over the next few years, however, it became clear that HTML was doing too much, and the W3C and other groups re‐ factored appearance, behavior, and many semantics into separate specifications:

• Cascading Style Sheets (CSS) took responsibility for presentation and layout. • JavaScript took responsibility for behavior, aided by the Docu‐ ment Object Model (DOM) and a variety of for handling device and multimedia interactions.

1 • WAI-ARIA took responsibility for semantics, ensur‐ ing that content remained available to a broad audience even if developers pushed the current boundaries of markup.

It’s not a completely neat separation—some of CSS feels like behavior, and JavaScript can manipulate presentation, for example, but they certainly took some work off the shoulders of HTML. A few aspects of HTML, notably media inclusion, are still mostly handled at the markup level, but most of them aren’t any longer. Forms and linking are both still defined in HTML itself, but they aren’t difficult to im‐ plement separately. When the WHATWG formed, its focus on develop‐ ment led it to build a variety of JavaScript tools, which still dominate the HTML5 work. In many ways, HTML5 has been about adding a few pieces of markup functionality to HTML itself and a tremendous pile of JavaScript APIs to browsers in general. Browsers still need to do a lot of work to achieve the visions developers have for a unified distributed application platform, but HTML itself carries less and less of that burden. The former flagship spec may be what comes to mind first when people say “web development,” but the reality is that it has been hollowed out. The heavy lifting happens in the other specifications. This means that we can free markup semantics from the demands originally placed on HTML. Markup doesn’t become total anarchy: defined markup syntax, both XML’s stricter version and HTML5’s more forgiving version, is still useful to create a parse tree browsers can decorate with CSS and WAI-ARIA and then manipulate with JavaScript. HTML itself is still useful—many people and tools know how to read and write it—but there is less and less reason to let the HTML vo‐ cabulary be a cage limiting our possibilities. Polyfills emerged as tools for bringing older browsers up to date with the latest specifications. Best practices for using them are still emerging, but they’ve become a more common implementation in frameworks like AngularJS, mak‐ ing it easy for developers to create markup templates that JavaScript will later manipulate. (The Web Components spec simplifies this work and provides structure that works across browsers reliably.) A stronger case for polyfills, though it was actually meant to argue for adding an element to the standard, comes from the picture element

2 | HTML: Moving Beyond the Standard saga. The Responsive Images Community Group developed a speci‐ fication and implemented it (twice) with polyfills. Those developers weren’t happy when the W3C and WHATWG didn’t seem interested (conversations continue), but from my perspective, they’d already done great work in creating the polyfills. (Loading media has more complicated optimization issues than just about anything else brows‐ ers do with HTML.) Shifting the focus away from markup standards is difficult. The Project spent a decade or so (and I participated) evangeliz‐ ing the need for web standards and disbanded recently in the face of success. The message that web tools need to be designed by a central organization is, for better or worse, deeply ingrained, but it’s time for markup to fall out of that story.1 HTML’s legacy vocabulary is a great foundation on which developers can build their own toolsets. The Web will benefit, however, from let‐ ting developers solve their information problems in their own ways, rather than trying to stuff too many things into a single vocabulary. Even if centralized markup standards have benefits, let’s evolve them rather than design them. So where should you start? The Polymer framework is a good place to experiment, and there’s been a lot of useful conversation at the Exten‐ sible Web Community Group. It’s early yet—this approach hasn’t be‐ come a standard part of developing a or app—but it’s time to start playing.

1. I’m not quite ready to join Matthew Butterick in proposing “that the W3C be disban‐ ded.” The W3C (and WHATWG) are still doing good work developing the supporting infrastructure of CSS, WAI-ARIA, and JavaScript APIs. ECMA-262 continues their work on JavaScript. The W3C and the browser vendors still have many great things to do to enhance the ways that browsers support markup processing.

HTML: Moving Beyond the Standard | 3

The Power of Markup

Markup with some brilliantly minimal hypertext options launched the World Wide Web. The toolset was approachable, easy to apply to many kinds of information, and laid the foundation for greater things to come. In the early days of HTML, it became clear pretty quickly that there were sane and insane ways to use markup. Some approaches, praised (or sometimes mocked) as “semantic” approaches, made it much sim‐ pler to apply Cascading Style Sheets (CSS) to documents and manip‐ ulate their structure and content with JavaScript. Even when I was first writing about Dynamic HTML, starting from a clean document made everything so much easier. (XHTML got traction among at least part of the Web community for just those kinds of reasons.) When I first got to XML, the markup was still primary and the pro‐ cessing an afterthought. Get the markup right—for many different values of right, of course—and the processing will be manageable. The markup approach offers some powers that I haven’t found in other data models and systems:

• Markup makes declarative approaches feel natural, with a natural “this goes here” system. • The very term “markup” reminds us that we are indeed marking up documents that may have cohesive value on their own, not just as shredded and codified chunks of data. • Broken and incomplete documents may yet contain especially important information. • Markup leaves the door open for information that didn’t fit in someone’s prized model, allowing for format evolution rather

5 than cycles of standardization. The structure of a given document is almost always easier to change than the programs that process it. (The nodes view emphasizes the priority of programs and all too often celebrates the things that make them brittle.) • Markup makes comprehensible possibilities that can’t be reached if you lock yourself into nodes from the beginning, like overlap‐ ping structures. Programmers indoctrinated into neat structure often see this as an utter corner case, but those who work with human documents know it exists regularly in the wild.

At some point, maybe around the time of the Microsoft “he doesn’t know what XML is” advertisement, a lot of people arrived in markup who had no interest in its details. XML was exciting because it made clear that data interchange was possible with much simpler tools than its predecessors. Markup was still incredibly useful, but as the servant of programmers. XML struc‐ tures suddenly had to look like programming structures, because nothing else could be trusted. They could look a little different, because after all, programmers from different environments had different ex‐ pectations, and there were documents to tolerate, but Schemas and WSDL and similarly structured approaches dominated. More recently, the rise of web applications has brought a similar chal‐ lenge to the HTML side of the markup story. Single-page apps often carry a tiny bit of markup that launches a JavaScript program, which then sets about creating an abstract vision of HTML elements in the DOM. Instead of layering their code on top of markup, the code takes over, and the HTML lingers only as a readable serialization for de‐ bugging. The data hygiene and mental hygiene of programming are not appro‐ priate for markup. Programming and markup have connections, much like carpentry and plumbing, but their best practices are very different. JSON, ASN.1, and similar approaches are much better fits for pro‐ gramming, which need only the structure but not the weight of mark‐ up. Over time, they (JSON in particular) are eroding XML’s share of markets it was never well suited for anyway. On the HTML side, I see some return to an appreciation of the value of markup. Content-first approaches to responsive can take advantage not only of the concrete nature of markup as a foun‐

6 | The Power of Markup dation for CSS described in “CSS Selectors Have Superpowers”, but also its flexibility—sketching in markup isn’t that hard. Hopefully Web Components will make it much easier in the near future, letting many more people enrich the HTML vocabulary with minimal disruption, as described in “HTML: Moving Beyond the Standard”. Even on the more programming-centric side, I see this piece on Isomorphic Java‐ Script suggesting a path forward that at least exposes more HTML on the Web rather than hiding information beyond JavaScript and APIs. Markup isn’t done yet.

The Power of Markup | 7

CSS Selectors Have Superpowers

After years of complaints about Cascading Style Sheets, many stem‐ ming from their deliberately declarative nature, it’s time to recognize their power. For developers coming from imperative programming styles, it might seem hard to lose the ability to specify more complex logical . That loss, though, is discipline leading toward the ability to create vastly more flexible systems, a first step toward the pattern- matching model common to functional programming. Way back when I was writing about styling XML in browsers, I didn’t even have to stop to think about how difficult it would be to repurpose CSS selectors for XML documents. Since they weren’t tightly bound to assumptions about HTML beyond the existence of elements and attributes, they just worked. The tool that most vividly demonstrated the real power of selectors, though, was jQuery. I may have annoyed some people by referring to jQuery as “that framework that lets you use CSS selectors instead of DOM tree walking” for a while, but Remy Sharp makes clear the power of that: The ease in which jQuery could be learnt was the appeal to me. All the DOM navigation was done using CSS expression using some in‐ sane black box magic that John Resig had come up [with]--saving my limited brain power, and once I had those DOM nodes, I could do what I wanted to them (usually some combinations of showing, hid‐ ing, fading and so on). Over time, as Sharp notes, Web browsers learned from jQuery, build‐ ing this basic lesson deeper into their tools and making it work more efficiently:

9 In those 7 years, quite a bit has happened. Probably one of the most important steps forward was the introduction of querySelectorAll. Being able to give a native function of a browser a CSS expression, and it doing the work to navigate the DOM is a huge (literally) part of jQuery. CSS selectors simplified the learning process, but they also simplified the resulting code. Figuring out which node an expression had selected became much, much simpler. Developers could apply the same selec‐ tors they were using for code to a stylesheet and quickly resolve any questions, and they could readily apply the same stylesheet to multiple documents if there were further questions. Why does this work so well, when CSS selectors offer only a few op‐ tions and a little logic? Declarative approaches work extremely well for describing queries through a document. Markup (whether HTML or XML) provides clear hooks for those queries through their element and attribute structures. The queries developers used to do by hunting and pecking through the DOM are still available, but most of the time, declarations will get you there a lot faster, or in identical time. Browsers can optimize their CSS selector processing, running it in much faster native code. A few years ago, I was very surprised to find that completely switching out stylesheets was faster than making a few style changes through JavaScript directly. Tree walking in JavaScript means a lot of back and forth between the document object and the interpreted code. Performance and ease of learning aren’t all you get, though. You also get a style of programming that offers vastly more flexibility, because selectors are a of pattern matching. Pattern-matching ap‐ proaches don’t require that all the patterns match—it is perfectly ac‐ ceptable to the pattern-matching engine for some patterns to match nothing and for some content to go unmatched. That makes it easy to build stylesheets that apply to a wide variety of differently structured documents, or to write code that only applies event handlers or other processing to elements if and when it finds a match. It’s a simple message often explained to beginners at the very start of learning CSS, but it reverberates throughout CSS practice. Stylesheets can be shared, reused, and applied in layers through the cascade that determines which declaration applies where.

10 | CSS Selectors Have Superpowers Adding to that flexibility, CSS can work with any markup vocabulary. There are some selectors that are tightly bound to HTML expectations of classes and IDs, but they are mostly syntax sugar. Selecting the same content in another vocabulary might require a few more characters and a bit more processing, but it is always possible and generally easy. Selectors give developers the freedom to create and use new vocabu‐ laries in the browser. Used in style sheets, they let developers tell browsers how to present content the browser doesn’t intrinsically un‐ derstand. Used in JavaScript, they let developers tell browsers what behavior to give new elements and attributes mixed into HTML. The result: polyfills, the development style described in “HTML: Moving Beyond the Standard”, which I suspect is the future of web develop‐ ment. Pattern matching has promise for markup processing beyond the browser. Historically, that’s mostly been done with XPath and XSLT or with other language combinations rather than CSS selectors, but CSS selectors are spreading even there, on the vectors of JavaScript on the server and testing tools. My long-term hope is that the success of CSS selectors will bring de‐ velopers to look for other ways to apply pattern matching to their markup, acting as a gateway to more declarative approaches that will add some much needed flexibility to code and document structures. All these quiet years later, CSS selectors seem to be our best bet for changing how we write code for the Web. (You can, of course, extend CSS with tools like SASS and LESS. You’ll still find CSS selectors a key part of that work!)

CSS Selectors Have Superpowers | 11

JavaScript: Not as Expected

JavaScript’s ever-growing importance still takes people by surprise. When I post about things JavaScript makes possible, I get pushback from people who refuse to be impressed by JavaScript. Why? Because it isn’t what they wanted. I’ve heard from a variety of quarters about how JavaScript is half Lisp, and terrible either because it dares to be half Lisp or because it only manages to be half Lisp. Similarly, as functional programming has become more visible, I’ve heard more from people who think Java‐ Script programming is too functional or not functional enough. Peo‐ ple disappointed in JavaScript because it doesn’t have strong typing are a constant, as are people who find prototypal inheritance perverse. JavaScript syntax doesn’t help. It’s tempting to tell the story of JavaScript as a series of historical ac‐ cidents. Brendan Eich put together LiveScript, applying a variety of techniques to meet a particular set of needs quickly. Since then, we’ve been dealing with JavaScript’s shift from a simple object manipulation language to a much broader and more powerful toolkit, unable to change approach because of the unique dynamics of the browser world. The more I think about this, though, the less I think it’s true. JavaScript has faced competition on various fronts for most of its existence:

• VBScript was an early contender, one that was more approachable for at least some kinds of development, though it was hobbled by Microsoft’s ownership. • Java applets, of course, were supposed to do most of the work we do today with JavaScript-based web applications. Many of the

13 applet dreams would have shrunk the Web to simple documents and containers for applets. • Flash carried its own banner for years. Of course, ActionScript is itself a dialect of JavaScript, but the tools and environment were very different. Flash and JavaScript development were generally seen as competitive, especially as HTML5 added multimedia fea‐ tures that had previously required Flash.

Perhaps all of those opponents were flawed, and perhaps JavaScript’s ubiquity was truly a strange accident. Perhaps, though, JavaScript actually fits its role well. It’s survived the shift from event handlers specified in the HTML to unobtrusive ap‐ proaches. JavaScript syntax has proven extensible enough to support chained function calls. As discussed in “CSS Selectors Have Super‐ powers”, JavaScript tools have adopted CSS selectors to simplify in‐ teractions with the document tree, cleaning up one of the longest- standing headaches. JavaScript’s asynchronous event handling has even found a new home on the server, a key part of Node’s approach to scale. Many of the shiniest parts of HTML5 are also JavaScript APIs, not new markup. Even if JavaScript isn’t the perfect language so many programmers would like it to be, it’s proven remarkably flexible, adjusting itself to the needs of the moment. Its latest act, described in “Will JavaScript Take Over the Programming World?”, which may keep it from con‐ quering the world through ubiquity, is even a disappearing act. The developers who’ve hated it for years may find its flexibility so powerful that they can compile other languages to it, rather than dealing with JavaScript directly. I wonder, though, whether there’s another round of JavaScript appre‐ ciation to come. The years since JavaScript: The Good Parts have seen a steady increase in the number of programmers who take JavaScript seriously. Programming culture hasn’t yet embraced JavaScript as a first language: web developers may learn it as their first programming language, but programmers tend to start elsewhere. In a perverse way, compilation to JavaScript may increase appreciation of JavaScript’s flexibility (at least among a few who realize what’s happening).

14 | JavaScript: Not as Expected JavaScript’s differences, though, don’t seem to have hurt it. Despite some pieces that seem odd to developers coming from other back‐ grounds, those differences have helped JavaScript usage evolve with the Web.

JavaScript: Not as Expected | 15

From JavaScript to Declarative Markup

Web architecture separates structured content (markup), presentation (style), and behavior (JavaScript). As recently as a decade ago, many developers worked in all three, but the years since arrived have brought more specialization. The rise of JavaScript in particular has led to approaches that have JavaScript carry the load. I’ve been de‐ lighted to see work that suggests a different path forward, one that takes greater advantage of the flexibility markup offers. At the Artifact Conference, I was delighted to return to the world of web designers. The crowd was full of people who know very well what JavaScript can add to their site and how they want to include it, but who also don’t focus on it. JavaScript is just a tool, often even a tool wielded later in the process after the basic framing of the site is com‐ plete. Though the emphasis on design meant that many people were still enthusiastic about creating comps in Photoshop, one of my favorite talks included Jen Simmons emphasizing an HTML-first approach to page building: getting the structure of the document right before fo‐ cusing on either style or behavior. The unstyled HTML she showed from the New York Times made clear the tangles that emerge from thinking of markup as just a byproduct of the other work done to build the site. Other talks explored complex interactions between browsers, markup, and styling needed to make work. Polymer, a project that makes HTML usefully extensible, is a good place to explore. Instead of creating a JavaScript program that deals with the entire page, Polymer focuses on JavaScript modules that deal

17 with specific markup, markup you can choose. (It can still work with those programs, of course!) While I love that Polymer is a surprisingly sudden implementation of ideas I suggested in “HTML: Moving Beyond the Standard”, the part I like better is that this approach to problem solving makes it easier to include the designers I talked with at Artifact. New markup offering new capabilities is great, especially when it can be styled with familiar tools. Though it’s early, the Polymer approach promises a much easier conversation between designers, programmers, and the developers combining aspects of both. Does this new markup extensibility mean that JavaScript developers will have less to do as modularization simplifies sharing? I don’t think so. In Extend the Web Forward, Yehuda Katz suggests that there is a lot more extending to do: When the browser has good extension points (or any extension points, really), we live in a virtuous cycle… If things are working well, JavaScript library authors write new de‐ clarative APIs that the browser can roll in. Nobody wants to write everything using low-level calls to canvas, but we’re happy that canvas lets us express low-level things that we can evolve and refine. Katz doesn’t claim it will be easy. He worries about “extension points that can be performance footguns.” He does, however, see the constant flow from imperative JavaScript APIs to more declarative approaches as the path forward. To me, that seems like the right way to balance flexibility with usability.

18 | From JavaScript to Declarative Markup Toward Responsive Web Programming

“Expect the unexpected” has long been a maxim of web development. New browsers and devices arrive, technologies change, and things break. The lore of web development isn’t just the technology: it ad‐ dresses the many challenges of dealing with customers who want to lock everything down. Matt Griffin (and a lot of others) reminded me of these difficulties at Artifact, and his Client Relationships and the Multi-Device Web brings it home for designers. Is there room for programmers to tell a similar story? I don’t mean agile. Agile development is difficult enough to explain to clients, but applications that adapt to their circumstances are a separate set of complications. Iterating on adaptable behaviors may be more difficult than iterating on adaptable designs, but it opens new possi‐ bilities both for applications and for the evolution of the Web. Responsive Web Design is (slowly) becoming the new baseline, giving designers a set of tools for building pages that (usually) provide the same functionality while adapting to different circumstances. Pro‐ grammers sometimes provide different functionality to different users, but it’s more often about cases where users have different priv‐ ileges than about different devices and contexts. Adjusting how content displays is complex enough, but modifying application behavior to respond to different circumstances is more unusual. The goal of most web development has been to provide a single experience across a variety of devices, filling in gaps whenever

19 possible to support uniformity. The history of “this page best viewed on my preferred browser” is mostly ugly. Polyfills, which I think have a bright future (as described in “HTML: Moving Beyond the Standard”), emerged to create uniformity where browsers didn’t. Browsers, though, now provide a huge shared context. Variations exist, of course, and cause headaches, but many HTML5 APIs and CSS3 features can work nicely as supplements to a broader site. Yes, you could build a web app around WebRTC and Media Capture and Streams, and it would only run on and Chrome right now. But you could also use WebRTC to help users talk about content that’s visible across browsers, and only the users on Firefox and Chrome would have the extra video option. The Web Audio API is also a good candidate for this, as might be some graphics features. This is harder, of course, with things like that provide basic functionality. For those cases, polyfills seem like a better option. Something that seems as complicated and foundational as Index‐ edDB could be made optional, though, by switching whether data is stored locally or remotely (or both). HTML5 and CSS3 have reawakened web development. I’m hoping that we can develop new practices that let us take advantage of these tools without having to wait for them to work everywhere. In the long run, I hope that will create a more active testing and development process to give browser vendors feedback earlier—but getting there will require changing the expectations of our users and customers as well.

20 | Toward Responsive Web Programming Will JavaScript Take Over the Programming World?

Last July, I had to give an impromptu talk. What came out, much to my surprise, was roughly: “JavaScript will dominate the programming world.” I didn’t say that JavaScript would dominate through sheer popularity—JavaScript may in fact top the list of languages disliked by programmers, because so many programmers use it as a strictly sec‐ ondary language beside their preferred server-side toolkit. Instead, I argued, as you’ll see in “Concentration: The Wrong Story” on page 21, that JavaScript would win by ubiquity, offering a solution that fits well enough in both clients and servers. While I still think JavaScript could indeed “fit well enough,” the winds have changed, and JavaScript may be about to surrender its ubiquity advantage, as you’ll see in “Dispersion: A More Likely Story?” on page 24. Concentration: The Wrong Story After decades of a Cambrian explosion, we may finally see a concen‐ tration in the use of a few programming languages and a correspond‐ ing decline of many others, leaving us with three main families of programming languages. (Remember, this story is wrong.) C and its immediate relatives will always be with us, providing a thin abstraction layer just above the processor. Functional languages that trade off ease of use in favor of extreme reliability, scalability, and manageability will continue to thrive in a small but ever-more impor‐ tant space. The biggest changes, though, will happen to the currently diverse general-purpose languages.

21 General-purpose languages, the tools that programmers have used to quickly assemble programs without having to sweat the details of memory management and data structures, are approaching a turning point. There is nothing intrinsically wrong with Perl, Python, Ruby, PHP, Java, C#, or many others, and they will continue to be used for a long time. However, their growth rates are going to shrink dramati‐ cally. What innovation could unseat those champions? It’s “the VB of the Web,” a language that was patronized and dismissed for over a decade. JavaScript may not have had much respect for a very long time, but it has two major advantages over all of its general-purpose competitors: Ubiquity JavaScript is available on practically every computer sold today, and any programmer who’s gone near the Web has at least thought about it. Power The JavaScript renaissance continues to demonstrate that this language is extremely capable, especially in the ever-growing number of cases where asynchronous communications are nec‐ essary. JavaScript snuck in. For a long time, “write once run anywhere” was supposed to mean Java, with its armies of virtual machines for every platform. The browser was just a window into a server-based world, with JavaScript providing a few key features on the client. As devel‐ opers realized that the Web was the easiest way to create user interfaces for shared data, more and more programming activity shifted away from classic GUI implementation to building web applications. As more and more Java development fell back to the server, JavaScript solidified its hold on the client. While the Dynamic HTML boomlet of the late 90s vanished into the dot-com bust, Ajax returned JavaScript to prominence in 2005. Doug‐ las Crockford’s JavaScript: The Good Parts made it clear that JavaScript was a first-class programming language, even if its take on objects was unconventional. Growing demand for more desktop-like user expe‐ riences led to massive growth in JavaScript programming, with more processing happening in the browser. That often (though not always) led to simplification on the server side.

22 | Will JavaScript Take Over the Programming World? Having achieved ubiquity as THE language (pretty much the only language) for client-side web programming, JavaScript is now poised to take over the server as well. It is not just possible to program the server-side components of a web application in JavaScript, but Java‐ Script has certain key advantages other languages can’t compete with:

• JavaScript’s years of use in interfaces created a dominant callback style that works efficiently in pretty much any asynchronous com‐ munications situation. • Browsers now run on an incredibly wide variety of devices, from cellphones with slow CPUs and lousy bandwidth to speedy ma‐ chines with lots of bandwidth. Using JavaScript lets applications decide where they want the code to run, and new frameworks (notably but not exclusively Mojito) can decide based on a given situation whether JavaScript should run on the client or the server.

It is probably possible to create a language with as much support for async as JavaScript, and a better syntax. It probably also makes sense to compile that language to JavaScript, as both CoffeeScript and Dart do. The second advantage is much, much harder to overcome. It’s certainly possible for something like GWT to compile Java to JavaScript, but it’s a difficult thing to sustain. RJS (Ruby compiled to JavaScript) became a dead end pretty quickly. JavaScript may be a great target for com‐ pilers, as CoffeeScript and Dart are demonstrating, but those languag‐ es typically retain many of the restrictions and values of JavaScript. The JavaScript community itself is evolving to support these new pos‐ sibilities. Node is the hot and new server-side environment (complete with surprising support from Microsoft), but perhaps more impor‐ tantly, it’s spawning an ever-growing number of extensions and frame‐ works. Most of those are small pieces, but “full-stack” frameworks, notably Meteor, are emerging to cover the entire range of tasks from querying databases to helping users interact with that data. Wait five years, and there won’t be much good reason to use other languages to build web applications. Wait 10 years, and you’ll see ap‐ plications written in other languages migrating to JavaScript because of the enormous ecosystem it’s building. Because so many program‐ mers use JavaScript at least “part-time,” it’s not hard to find program‐ mers for JavaScript projects. JavaScript’s lack of a corporate master (a

Concentration: The Wrong Story | 23 difficulty in its early years) gives it an advantage moving forward be‐ cause users don’t have to fear corporate agendas. Other languages will probably not go extinct, but it will be much more difficult for them to grow. My suspicion would be that they find smaller niches, with Python perhaps holding on in the sciences, Ruby in ex‐ perimental development, Java and C# in some corporate systems, and Perl in text processing and data munging. They will all still be good at what they do, but will face sharper competition. I was, of course, wrong. Dispersion: A More Likely Story? I no longer forecast JavaScript taking over the general-purpose lan‐ guage space. It’s not because polyglot (multilanguage) programming is more fun or even more powerful for most cases. It’s because I was wrong about the side effects of compiling to JavaScript. When I first told this story, compilation to JavaScript was exciting but tricky. It was spreading from GWT to Dart to ClojureScript to Cof‐ feeScript, but it seemed likely to always remain special purpose, buffer‐ ing a larger shift toward JavaScript but incapable of slowing down a growing shift. Over the last few months, though, I’ve been surprised by continuing conversations about JavaScript as a new assembly language—certainly more approachable than my distant memories of 6502, but similarly flexible. Asm.js broadened that conversation dramatically. While I re‐ main uncertain that it will be the one true approach, it makes it very clear that the compilation approach can be more generic than I had thought possible. Compilation approaches mean that “the JavaScript way” will no longer be the only way to do things in the spaces where JavaScript currently dominates. This frees developers who don’t especially like the Java‐ Script way to work with approaches that they’re more comfortable with. Even developers who are fond of JavaScript may take the op‐ portunity to experiment with something different as toolsets grow and it becomes easier to do.

24 | Will JavaScript Take Over the Programming World? The Cambrian explosion I mentioned earlier may be returning—to JavaScript itself. Asm.js and related work moves programming an‐ other layer up the abstraction stack. Our processors seem capable of handling the known inefficiencies, and our toolsets seem prepared for another bout of rapid evolution.

Dispersion: A More Likely Story? | 25 About the Author Simon St.Laurent is Senior Editor at O’Reilly Media, Inc., focusing primarily on JavaScript and web-related projects. He is co-chair of the Fluent and OSCON conferences. He’s authored or coauthored books including Introducing Elixir, Introducing Erlang, Learning Rails 3, XML Pocket Reference, Third Edition,, XML: A Primer, and Cookies.