Posts

Showing posts from 2013

Printing Markdown files on GitHub

GitHub displays Markdown files so nicely, it’s a shame there is no print view where all the toolbars etc. are hidden. Note that printing doesn’t necessarily mean that paper is involved. For example, on Mac OS X, you can print to PDF files. This blog post explains three ways of printing Markdown files that are hosted on GitHub: Markdown tools: such as kramdown can be used to turn Markdown files into HTML files that can be printed. Safari’s Reader mode [1] : With many pages, Safari displays a “Reader” button in the address bar. Clicking it usually removes all clutter around content. You can print a page in Reader mode. Disadvantage of this solution (especially compared to the next one): You lose most of the syntax highlighting of source code. Bookmarklet [2] : Create a bookmark with the following URL, click it and everything around the content is removed. javascript:var content = document. querySelector('article'); var body = document.quer

JavaScript gains support for SIMD

Recently , a new JavaScript feature has landed for the next Firefox Nightly: an API for SIMD (Single Instruction, Multiple Data). This blog post explains how the API works and how it fits into the JavaScript landscape. What is SIMD? SIMD is the ability of a CPU to apply an operand to vectors of values, instead of single values. For example, a CPU may be able to add two vectors v and w by adding their components, hence applying the single instruction addition to multiple data: v + w = 〈v 1 , …, v n 〉+ 〈w 1 , …, w n 〉 = 〈v 1 +w 1 , …, v n +w n 〉 SIMD brings speed-ups to many kinds of number crunching (3D computations, image processing, singal processing, etc.). John McCutchan (Google) and Peter Jensen (Intel) have proposed a JavaScript API for SIMD. That API initially grew out of the SIMD support in Dart, because Dart SIMD code needed to be compiled to JavaScript. At the moment, the API provides two data types: float32x4 (C type: __m128): four 32 bit floating point n

ECMAScript 6: the new array methods find() and findIndex()

Update 2014-05-08. Newer version of this post: “ ECMAScript 6’s new array methods ” Two new Array methods (proposed by Rick Waldron) are in the latest ECMAScript 6 specification draft: Array.prototype.find() Array.prototype.findIndex() This blog post describes them. Array.prototype.find(predicate, thisValue?) The signature of the callback predicate() is predicate(element, index, array) find() iterates over the array (while skipping holes) and calls predicate for each element. If predicate returns true , find() stops iterating and returns the current element (1). If the callback never returns true , find() returns undefined (2). This method could be implemented as follows. Array.prototype.find = function (predicate, thisValue) { var arr = Object(this); if (typeof predicate !== 'function') { throw new TypeError(); } for(var i=0; i < arr.length; i++) { if (i in arr) { // skip holes

ParallelJS: data parallelism for JavaScript

Updates: [2015-01-05] ParallelJS has failed . It apparently wasn’t powerful enough. Its experimental implementation will be removed from SpiderMonkey (Firefox’s JavaScript engine). [2013-12-28] A low-level JavaScript API for SIMD is another avenue for parallelization (within a single processer core). JavaScript is still a very sequential language. That is slowly changing. This blog post describes ParallelJS , an effort to bring data parallelism to JavaScript. Background Concurrency versus parallelism Parallelism: more than one task is executed at the same time. That means that the tasks run on different processors or processor cores. Concurrency: more than one task makes progress at the same time. Often, tasks depend on each other. Concurrent tasks may run in parallel, but they can also be run via time slicing (virtual parallelism, if you will). These terms are not always used precisely, but the context usually makes it clear what is meant. Kinds of

Using strict mode in the Node.js REPL

If you want to use strict mode [1] in the Node.js REPL , you have two options. Option 1. Start the REPL as usual, wrap your code in an IIFE [2] : > (function () { 'use strict'; 'abc'.length = 1 }()); TypeError: Cannot assign to read only property 'length' (Assigning to a read-only property fails silently in sloppy mode.) Option 2. Use the Node.js command line option --use_strict : node --use_strict Afterwards, everything you write in the REPL is interpreted in strict mode: > 'abc'.length = 1 TypeError: Cannot assign to read only property 'length' References: JavaScript’s strict mode: a summary JavaScript variable scoping and its pitfalls

Man In The Mirror

Image
The Conversion of St. Paul, 1767 by Nicolas-Bernard Lepicie I’ve spent the last few months on self-imposed sabbatical to read and write about St. Paul, a guy, as it turns out, I didn’t like very much.   After reading a biography of Charles Manson last summer, I found more connections between Charlie and Paul than I did between other apostle-saints and Paul.   In fact, Paul fits the profile of exactly what he was:   a cult leader.   By force of will and personality, he cajoled, bullied, commanded, and guilted others into following his lead.   When they didn’t do what he wanted, his rage was legendary. The part of the research I became obsessed with was the way Paul changed his life.   There are two stories about his “conversion”:   one where he is knocked to the ground by a flash of light and a voice demanding to know why he is persecuting the followers of Jesus; and two, a quieter, more internal change from persecutor to early Church leader.   Whatever story one believes, it is a sta

Why are there so many array-like objects in the DOM?

Tweet by Leon Arnott: #TIL the reason the DOM has so many "array-like objects" that aren't functional arrays… is because in Javascript 1.0, there were no arrays. Explanation: ECMAScript 1 does have arrays, but it corresponds to JavaScript 1.3. JavaScript version numbers apply to the JavaScript engines implemented by Netscape/Mozilla. The cross-engine way of referring to the capabilities of the language are thus ECMAScript versions. Arrays were indeed added after JavaScript 1, as this page shows, which lists the additions for version 1.1. More information on array-like objects and arrays: JavaScript quirk 8: array-like objects Arrays in JavaScript

Initializing an array with values

It is not a frequent use case, but it comes up occasionally: Producing an array [1] of a given length that is filled with values. This blog post explains how to do it and what to watch out for. Let us start with something simple: producing an array of length n whose first element is 0, second element is 1, etc. Array.prototype.map() Once you have an array with length n , you can use the array method map() to fill it appropriately. For example, to produce the array [0, 1, 2] , any array of length 3 will do: > var arr = [null, null, null]; > arr.map(function (x, i) { return i }) [ 0, 1, 2 ] Alas, map() skips holes, but preserves them [2] , which is why an empty array (with only holes) does not work for us: > new Array(3).map(function (x, i) { return i }) [ , , ] The next two sections look at ways of creating an array with a given length. Filling an array via apply() Function.prototype.apply() treats holes as if they were undefined elements [3] . Theref

ECMAScript 6 modules in future browsers

Update 2013-11-22: David Herman has published the slide deck “ Status Report: ES6 Modules ”. [1] is an introduction to ECMAScript 6 modules and how they can be used in current browsers. In contrast, this blog post explains how future browsers will support them natively. As part of that support, we will get the <module> tag, a better version of the <script> tag. Browsers: asynchronous modules, synchronous scripts Modules. To be in line with JavaScript’s usual run-to-completion semantics, the body of a module must be executed without interruption. That leaves two options for importing modules: Load modules synchronously, while the body is executed. That is what Node.js does. Load all modules asynchronously, before the body is executed. That is how AMD modules are handled. It is the only option for browsers, because modules are loaded over the internet. Otherwise, execution would pause for too long. As an added benefit, this approach allows one to load multipl

Immediately invoked constructors and object literals

By now, you are probably familiar with immediately invoked function expressions (IIFEs, [1] ). This blog post looks at immediately invoked constructors and immediately invoked object literals. Immediately invoked constructors Andrea Giammarchi (@WebReflection) recently reminded us that you can immediately invoke constructors. That is useful for setting up plain objects. Let’s look at a (slightly contrived) example: var obj = new function () { // open IIC var uid = computeUID(); this.first = 'Jane'; this.last = 'Doe'; this.uid = uid; }(); // close IIC The immediately invoked constructor provides you with a private scope, in which the variable uid lives. You can then use this to set up the instance that has been created by new . Additionally, new returns that instance for you. You can save a few characters by omitting the parentheses at the end: var obj = new function () { // open IIC ... }; // close IIC The

The history of “typeof null”

Update 2013-11-05: I take a look at the C code of typeof to better explain why typeof null results in 'object' . In JavaScript, typeof null is 'object' , which incorrectly suggests that null is an object (it isn’t, it’s a primitive value, consult my blog post on categorizing values for details). This is a bug and one that unfortunately can’t be fixed, because it would break existing code. Let’s explore the history of this bug. The “typeof null” bug is a remnant from the first version of JavaScript. In this version, values were stored in 32 bit units, which consisted of a small type tag (1–3 bits) and the actual data of the value. The type tags were stored in the lower bits of the units. There were five of them: 000: object. The data is a reference to an object. 1: int. The data is a 31 bit signed integer. 010: double. The data is a reference to a double floating point number. 100: string. The data is a reference to a string. 110

The dict pattern: objects without prototypes are better maps

Using objects as maps from strings to values has several pitfalls. This blog post describes a pattern that eliminates some of them. The pitfalls If you are (ab)using objects as maps from strings to values, you’ll encounter several pitfalls: Inherited properties prevent you from directly using the in operator for checking for a key and brackets for reading a value: > var empty = {}; // empty map > var key = 'toString'; > key in empty // should be false true > empty[key] // should be undefined [Function: toString] Map entries override methods, meaning that you can’t directly invoke methods on an object-as-map. You need to escape the key __proto__ , because it triggers special behavior in many JavaScript engines. For details on these pitfalls, consult the blog post “ The pitfalls of using objects as maps in JavaScript ”. The dict pattern The solution is to create an object without a prototype: var dict = Object.cr

The JavaScript console API

In most JavaScript engines, there is a global object console with methods for logging and debugging. That object is not part of the language proper, but has become a de facto standard, since being pioneered by the Firebug debugger. Since their main purpose is debugging, the console methods will most frequently be used during development and rarely in deployed code. This blog post gives an overview of the methods of console . How standardized is the console API across browsers? Firebug first provided the console API and the documentation in its wiki is the closest thing to a standard there is. Additionally, Brian Kardell and Paul Irish are working on a specification for the API, which should lead to more consistent behavior across browsers in the long term. Until then, behavior varies widely. Therefore, this blog post can only provide an overview. For details, you should consult the following documentation for various platforms: Chrome: developers.google.com/chrome-developer-too

Safe integers in JavaScript

Update 2014-02-08: Follow-up blog post “ What are integers in JavaScript? ” JavaScript can only safely represent integers i in the range −2 53 < i < 2 53 . This blog post examines why that is and what “safely represent” means. It is based on an email by Mark S. Miller to the es-discuss mailing list. Safe integers The idea of a safe integer is about how mathematical integers are represented in JavaScript. In the range (−2 53 , 2 53 ) (excluding the lower and upper bounds), JavaScript integers are safe : there is a one-to-one mapping between mathematical integers and their representations in JavaScript. Beyond this range, JavaScript integers are unsafe : two or more mathematical integers are represented as the same JavaScript integer. For example, starting at 2 53 , JavaScript can only represent every second mathematical integer. > Math.pow(2, 53) 9007199254740992 > Math.pow(2, 53)+1 9007199254740992 > Math.pow(2, 53)+2 9007199254740994 >

Tips for using window in JavaScript

In web browsers, window refers to an object that contains the global variables. This blog post explains how it works and when to use it. The global object and window The ECMAScript specification uses the internal data structure environment to store variables. The language has the somewhat unusual feature of making the environment for global variables accessible as an object, the so-called global object . The global object can be used to create, read and change global variables. In global scope, this points to it: > var foo = 'hello'; > this.foo // read global variable 'hello' > this.bar = 'world'; // create global variable > bar 'world' In web browsers, the global variable window also points to the global object. JavaScript creator Brendan Eich considers the global object one of his “ biggest regrets ”. Cross-platform considerations Node.js does not have a global variable window . Therefore, the only safe cross-p

Unicode and JavaScript

Update 2013-09-29: New sections 4.1 (“Matching any code unit”) and 4.2 (“Libraries”). This blog post is a brief introduction to Unicode and how it is handled in JavaScript. Unicode History Unicode was started in 1987, by Joe Becker (Xerox), Lee Collins (Apple) and Mark Davis (Apple). The idea was to create a universal character set, as there were many incompatible standards for encoding plain text at that time: numerous variations of 8 bit ASCII, Big Five (Traditional Chinese), GB 2312 (Simplified Chinese), etc. Before Unicode, no standard for multi-lingual plain text existed, but there were rich text systems (such as Apple’s WorldScript) that allowed one to combine multiple encodings. The first Unicode draft proposal was published in 1988. Work continued afterwards and the working group expanded. The Unicode Consortium was incorporated on January 3, 1991: The Unicode Consortium is a non-profit corporation devoted to developing, maintaining, and promoting software internationaliz