Planet JavaScript

the unofficial alterslash-style digest

Contents

  1. ECMAScript 6: maps and sets Axel Rauschmayer (②ality – JavaScript and more) @ München › Germany • over a year ago
  2. Introduction to HTML Imports Web Components Articles • over a year ago
  3. Databound, Typist Alex Young (DailyJS) @ London › England • over a year ago
  4. Curl Converter, aja.js, sneakpeek Alex Young (DailyJS) @ London › England • over a year ago
  5. Node Roundup: nchat, hulken, cult Alex Young (DailyJS) @ London › England • over a year ago
  6. A new Microsoft browser? Peter-Paul Koch (Quirks Blog) @ Amsterdam › Netherlands • over a year ago
  7. JavaScript: 2014 in Review Alex Young (DailyJS) @ London › England • over a year ago
  8. React-Grid-Layout, Angular Debug Bar and Reading Position Alex Young (DailyJS) @ London › England • over a year ago
  9. ngKookies, preCode.js Alex Young (DailyJS) @ London › England • over a year ago
  10. Symbols in ECMAScript 6 Axel Rauschmayer (②ality – JavaScript and more) @ München › Germany • over a year ago
  11. Dynamic-json-resume, JSnoX Alex Young (DailyJS) @ London › England • over a year ago
  12. Holiday Hacking: Apps Alex Young (DailyJS) @ London › England • over a year ago
  13. Node Roundup: 0.10.35, Prettiest, Artisan Validator Alex Young (DailyJS) @ London › England • over a year ago
  14. Particle Paintings, AMD to CommonJS with Recast Alex Young (DailyJS) @ London › England • over a year ago
  15. ECMAScript 6: new OOP features besides classes Axel Rauschmayer (②ality – JavaScript and more) @ München › Germany • over a year ago

Among others, the following four data structures are new in ECMAScript 6: Map, WeakMap, Set and WeakSet. This blog post explains how they work.

Map

JavaScript has always had a very spartan standard library. Sorely missing was a data structure for mapping values to values. The best you can get in ECMAScript 5 is a map from strings to arbitrary values, by abusing objects. Even then there are several pitfalls that can trip you up.

The Map data structure in ECMAScript 6 lets you use arbitrary values as keys and is highly welcome.

Basic operations

Working with single entries:

    > let map = new Map();
    
    > map.set('foo', 123);
    > map.get('foo')
    123
    
    > map.has('foo')
    true
    > map.delete('foo')
    true
    > map.has('foo')
    false

Determining the size of a map and clearing it:

    > let map = new Map();
    > map.set('foo', true);
    > map.set('bar', false);
    
    > map.size
    2
    > map.clear();
    > map.size
    0

Setting up a map

You can set up a map via an iterable over key-value “pairs” (arrays with 2 elements). One possibility is to use an array (which is iterable):

    let map = new Map([
        [ 1, 'one' ],
        [ 2, 'two' ],
        [ 3, 'three' ], // trailing comma is ignored
    ]);

Alternatively, the set method is chainable:

    let map = new Map()
    .set(1, 'one')
    .set(2, 'two')
    .set(3, 'three');

Keys

Any value can be a key, even an object:

    let map = new Map();
    
    const KEY1 = {};
    map.set(KEY1, 'hello');
    console.log(map.get(KEY1)); // hello
    
    const KEY2 = {};
    map.set(KEY2, 'world');
    console.log(map.get(KEY2)); // world
What keys are considered equal?

Most map operations need to check whether a value is equal to one of the keys. They do so via the internal operation SameValueZero, which works like === [1], but considers NaN to be equal to itself.

Let’s first see how === handles NaN:

    > NaN === NaN
    false

Conversely, you can use NaN as a key in maps, just like any other value:

    > let map = new Map();
    
    > map.set(NaN, 123);
    > map.get(NaN)
    123

Like ===, -0 and +0 are considered the same value (which is the best way to handle the two zeros [3]).

    > map.set(-0, 123);
    > map.get(+0)
    123

Different objects are always considered different. That is something that can’t be configured (yet), as explained later, in the FAQ.

    > new Map().set({}, 1).set({}, 2).size
    2

Getting an unknown key produces undefined:

    > new Map().get('asfddfsasadf')
    undefined

Iterating

Let’s set up a map to demonstrate how one can iterate over it.

    let map = new Map([
        [false, 'no'],
        [true,  'yes'],
    ]);

Maps record the order in which elements are inserted and honor that order when iterating over keys, values or entries.

Iterables for keys and values

keys() returns an iterable [4] over the keys in the map:

    for (let key of map.keys()) {
        console.log(key);
    }
    // Output:
    // false
    // true

values() returns an iterable over the values in the map:

    for (let value of map.values()) {
        console.log(value);
    }
    // Output:
    // no
    // yes
Iterables for entries

entries() returns the entries of the map as an iterable over [key,value] pairs (arrays).

    for (let entry of map.entries()) {
        console.log(entry[0], entry[1]);
    }
    // Output:
    // false no
    // true yes

Destructuring enables you to access the keys and values directly:

    for (let [key, value] of map.entries()) {
        console.log(key, value);
    }

The default way of iterating over a map is entries():

    > map[Symbol.iterator] === map.entries
    true

Thus, you can make the previous code snippet even shorter:

    for (let [key, value] of map) {
        console.log(key, value);
    }
Spreading iterables

The spread operator (...) turns an iterable into the arguments of a function or parameter call. For example, Math.max() accepts a variable amount of parameters. With the spread operator, you can apply that method to iterables.

    > let arr = [2, 11, -1];
    > Math.max(...arr)
    11

Spread also turns an iterable into the elements of an array. That lets us convert the result of Map.prototype.keys() (an iterable) into an array:

    let map = new Map([
        [1, 'one'],
        [2, 'two'],
        [3, 'three'],
    ]);
    let arr = [...map.keys()]; // [1, 2, 3]

Looping over entries

The Map method forEach has the following signature:

    Map.prototype.forEach((value, key, map) => void, thisArg?) : void

The signature of the first parameter mirrors the signature of the callback of Array.prototype.forEach, which is why the value comes first.

    let map = new Map([
        [false, 'no'],
        [true,  'yes'],
    ]);
    map.forEach((value, key) => {
        console.log(key, value);
    });
    // Output:
    // false no
    // true yes

Mapping and filtering

You can map() and filter() arrays, but there are no such operations for maps. The solution:

  1. Convert the map into an array of [key,value] pairs.
  2. Map or filter the array.
  3. Convert the result back to a map.

That’s what happens in the following example:

    let map0 = new Map()
    .set(1, 'a')
    .set(2, 'b')
    .set(3, 'c');
    
    let map1 = new Map(
        [...map0] // step 1
        .filter(([k, v]) => k < 3) // step 2
    ); // step 3
    // Resulting map: {1 => 'a', 2 => 'b'}
    
    let map2 = new Map(
        [...map0] // step 1
        .map(([k, v]) => [k * 2, '_' + v]) // step 2
    ); // step 3
    // Resulting map: {2 => '_a', 4 => '_b', 6 => '_c'}

Step 1 is performed by the spread operator (...) which I have explained previously.

Map API

Handling single entries:

  • Map.prototype.get(key) : any
    Returns the value that key is mapped to in this map. If there is no key key in this map, undefined is returned.

  • Map.prototype.set(key, value) : this
    Maps the given key to the given value. If there is already an entry whose key is key, it is updated. Otherwise, a new entry is created.

  • Map.prototype.has(key) : boolean
    Returns whether the given key exists in this map.

  • Map.prototype.delete(key) : boolean
    If there is an entry whose key is key, it is removed and true is returned. Otherwise, nothing happens and false is returned.

Handling all entries:

  • get Map.prototype.size : number
    Returns how many entries there are in this map.

  • Map.prototype.clear() : void
    Removes all entries from this map.

Iterating and looping: happens in the order in which entries were added to a map.

  • Map.prototype.entries() : Iterable<[any,any]>
    Returns an iterable with one [key,value] pair for each entry in this map. The pairs are arrays of length 2.

  • Map.prototype.forEach((value, key, collection) => void, thisArg?) : void
    The first parameter is a callback that is invoked once for each entry in this map. If thisArg is provided, this is set to it for each invocation. Otherwise, this is set to undefined.

  • Map.prototype.keys() : Iterable<any>
    Returns an iterable over all keys in this map.

  • Map.prototype.values() : Iterable<any>
    Returns an iterable over all values in this map.

  • Map.prototype[Symbol.iterator]() : Iterable<[any,any]>
    The default way of iterating over maps. Refers to Map.prototype.entries.

WeakMap

A WeakMap is a map that doesn’t prevent its keys from being garbage-collected. That means that you can associate data with objects without having to worry about memory leaks.

A WeakMap is a data structure whose keys must be objects and whose values can be arbitrary values. It has the same API as Map, with one significant difference: you can’t iterate over the contents – neither the keys, nor the values, nor the entries. You can’t clear a WeakMap, either.

The rationales for these restrictions are:

  • The volatility of WeakMaps makes iteration difficult.

  • Not having clear() provides a security property. Quoting Mark Miller: “The mapping from weakmap/key pair value can only be observed or affected by someone who has both the weakmap and the key. With clear(), someone with only the WeakMap would’ve been able to affect the WeakMap-and-key-to-value mapping.”

Using WeakMaps for private data

The following code uses the WeakMaps _counter and _action to store private data.

    let _counter = new WeakMap();
    let _action = new WeakMap();
    class Countdown {
        constructor(counter, action) {
            _counter.set(this, counter);
            _action.set(this, action);
        }
        dec() {
            let counter = _counter.get(this);
            if (counter < 1) return;
            counter--;
            _counter.set(this, counter);
            if (counter === 0) {
                _action.get(this)();
            }
        }
    }

Let’s use Countdown:

    > let c = new Countdown(2, () => console.log('DONE'));
    > c.dec();
    > c.dec();
    DONE

Because Countdown keeps instance-specific data elsewhere, its instance c has no own property keys:

    > Reflect.ownKeys(c)
    []

WeakMap API

WeakMaps have only four methods, all of them work the same as the Map methods.

  • WeakMap.prototype.get(key) : any
  • WeakMap.prototype.set(key, value) : this
  • WeakMap.prototype.has(key) : boolean
  • WeakMap.prototype.delete(key) : boolean

Set

ECMAScript 5 doesn’t have a set data structure, either. There are two possible work-arounds:

  • Use the keys of an object to store the elements of a set of strings.
  • Store (arbitrary) set elements in an array: Check whether it contains an element via indexOf(), remove elements via filter(), etc. This is not a very fast solution, but it’s easy to implement. One issue to be aware of is that indexOf() can’t find the value NaN.

ECMAScript 6 has the data structure Set which works for arbitrary values, is fast and handles NaN correctly.

Basic operations

Managing single elements:

    > let set = new Set();
    > set.add('red')
    
    > set.has('red')
    true
    > set.delete('red')
    true
    > set.has('red')
    false

Determining the size of a set and clearing it:

    > let set = new Set();
    > set.add('red')
    > set.add('green')
    
    > set.size
    2
    > set.clear();
    > set.size
    0

Setting up a set

You can set up a set via an iterable over the elements that make up the set. For example, via an array:

    let set = new Set(['red', 'green', 'blue']);

Alternatively, the add method is chainable:

    let set = new Set().add('red').add('green').add('blue');

Values

Like maps, elements are compared similarly to ===, with the exception of NaN being like any other value.

    > let set = new Set([NaN]);
    > set.size
    1
    > set.has(NaN)
    true

Adding an element a second time has no effect:

    > let set = new Set();
    
    > set.add('foo');
    > set.size
    1
    
    > set.add('foo');
    > set.size
    1

Similarly to ===, two different objects are never considered equal (which can’t currently be customized, as explained in the FAQ, later):

    > let set = new Set();
    
    > set.add({});
    > set.size
    1
    
    > set.add({});
    > set.size
    2

Iterating

Sets are iterable and the for-of loop works as you’d expect:

    let set = new Set(['red', 'green', 'blue']);
    for (let x of set) {
        console.log(x);
    }
    // Output:
    // red
    // green
    // blue

As you can see, sets preserve iteration order. That is, elements are always iterated over in the order in which they were inserted.

The previously explained spread operator (...) works with iterables and thus lets you convert a set to an array:

    let set = new Set(['red', 'green', 'blue']);
    let arr = [...set]; // ['red', 'green', 'blue']

We now have a concise way to convert an array to a set and back, which has the effect of eliminating duplicates from the array:

    let arr = [3, 5, 2, 2, 5, 5];
    let unique = [...new Set(arr)]; // [3, 5, 2]

Mapping and filtering

In contrast to arrays, sets don’t have the methods map() and filter(). A work-around is to convert them to arrays and back.

Mapping:

    let set = new Set([1, 2, 3]);
    set = new Set([...set].map(x => x * 2));
    // Resulting set: {2, 4, 6}

Filtering:

    let set = new Set([1, 2, 3, 4, 5]);
    set = new Set([...set].filter(x => (x % 2) == 0));
    // Resulting set: {2, 4}

API

Single set elements:

  • Set.prototype.add(value) : this
    Adds value to this set.

  • Set.prototype.has(value) : boolean
    Checks whether value is in this set.

  • Set.prototype.delete(value) : boolean
    Removes value from this set.

All set elements:

  • get Set.prototype.size : number
    Returns how many elements there are in this set.

  • Set.prototype.clear() : void
    Removes all elements from this set.

Iterating and looping:

  • Set.prototype.values() : Iterable<any>
    Returns an iterable over all elements of this set.

  • Set.prototype[Symbol.iterator]() : Iterable<any>
    The default way of iterating over sets. Points to Set.prototype.values.

  • Set.prototype.forEach((value, key, collection) => void, thisArg?)
    Loops over the elements of this set and invokes the callback (first parameter) for each one. value and key are both set to the element, so that this method works similarly to Map.prototype.forEach. If thisArg is provided, this is set to it for each call. Otherwise, this is set to undefined.

Symmetry with Map: The following two methods only exist so that the interface of sets is similar to the interface of maps. Each set element is handled as if it were a map entry whose key and value are the element.

  • Set.prototype.entries() : Iterable<[any,any]>
  • Set.prototype.keys() : Iterable<any>

WeakSet

A WeakSet is a set that doesn’t prevent its elements from being garbage-collected. Consult the section on WeakMap for an explanation of why WeakSets don’t allow iteration, looping and clearing.

Given that you can’t iterate over their elements, there are not that many use cases for WeakSets. They enable you to mark objects, to associate them with boolean values.

API

WeakSets have only three methods, all of them work the same as the Set methods.

  • WeakSet.prototype.add(value)
  • WeakSet.prototype.has(value)
  • WeakSet.prototype.delete(value)

FAQ

Why size and not length?

Question: Arrays have the property length to count the number of entries. Why do maps and set have a different property, size, for this purpose?

Answer: length is for sequences, data structures that are indexable – like arrays. size is for collections that are primarily unordered – like maps and sets.

Why can’t I configure how maps and sets compare keys and values?

Question: It would be nice if there were a way to configure what map keys and what set elements are considered equal. Why isn’t there?

Answer: That feature has been postponed, as it is difficult to implement properly and efficiently. One option is to hand callbacks to collections that specify equality.

Another option, available in Java, is to specify equality via a method that object implement (equals() in Java). However, this approach is problematic for mutable objects: In general, if an object changes, its “location” inside a collection has to change, as well. But that’s not what happens in Java. JavaScript will probably go the safer route of only enabling comparison by value for special immutable objects (so-called value objects). Comparison by value means that two values are considered equal if their contents are equal. Primitive values are compared by value in JavaScript.

References

  1. Equality Operators: === Versus ==” in “Speaking JavaScript”
  2. NaN” in “Speaking JavaScript”
  3. Two Zeros” in “Speaking JavaScript”
  4. Iterators and generators in ECMAScript 6

Introduction to HTML Imports

Web Components Articles Monday January 05, 2015 @ 00:00 • over a year ago

Template, Shadow DOM, and Custom Elements enable you to build UI components easier than before. But it's not efficient to load each resources such as HTML, CSS and JavaScript separately.

Deduping dependencies isn't easy either. To load a library like jQuery UI or Bootstrap today requires using separate tags for JavaScript, CSS, and Web Fonts. Things get even more complex if you deal with Web Components with multiple dependencies.

HTML Imports allow you to load those resources as an aggregated HTML file.


Using HTML Imports

In order to load an HTML file, add a link tag with an import in the rel attribute and an href that contains a path to the HTML file. For example, if you want to load an HTML file called component.html into index.html:

index.html

<link rel="import" href="component.html" >

You can load any resource including scripts, stylesheets, and web fonts, into the imported HTML just like you do to regular HTML files:

component.html

<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>

doctype, html, head, body aren't required. HTML Imports will immediately load the imported document, resolve subresources and execute JavaScript, if any.

Execution order

Browsers parse the content of HTML in linear order. This means script tags at the top of HTML will be executed earlier than the ones at the bottom. Also, note that browsers usually wait for any JavaScript code to finish executing before parsing the following lines of HTML.

In order to avoid script tag to block rendering of HTML, you can use async / defer attributes (or you can move all of your script tags to the bottom of the page). defer attribute postpones execution of the script until entire HTML is parsed. async attribute lets the browser asynchronously execute the script so it won't block rendering HTML.

Then, how do HTML Imports work?

Script inside an html import behave just like a script tag with a defer attribute. In the example code below, index.html will execute script1.js and script2.js inside component.html before executing script3.js.

index.html

<link rel="import" href="component.html"> // 1.
<title>Import Example</title>
<script src="script3.js"></script>        // 4.

component.html

<script src="js/script1.js"></script>     // 2.
<script src="js/script2.js"></script>     // 3.
  1. Loads component.html from index.html and wait for execution
  2. Execute script1.js in component.html
  3. Execute script2.js in component.html after execution of script1.js
  4. Execute script3.js in index.html after execution of script2.js

Note that by adding an async attribute to link[rel="import"], HTML Import behaves just like async attribute to script tag. It won't wait for the execution and load of imported HTML which also means it doesn't block rendering the original HTML. This can potentially improve performance of your website unless other scripts depends on the execution of the imported HTML.

Going beyond origins

HTML Imports basically can't import resources from other origins. For example, you can't import an HTML file at http://example.com/ from http://webcomponents.org/.

To avoid this restriction, use CORS (Cross Origin Resource Sharing). To learn about CORS, read this article.

window and document object in an imported HTML

Earlier, I mentioned JavaScript will be executed when an HTML file is imported. But this doesn't mean the markup in the imported HTML file will also be rendered inside the browser. You need to write some JavaScript to help here.

One caveat to using JavaScript with HTML Imports is that the document object in an imported HTML file actually points to the one in the original page.

Taking the previous code as an example, the document in index.html and component.html both refers to the document object in index.html.

So, how can you refer to the document object of the imported HTML file?

In order to obtain component.html's document object from within the index.html page, refer to the link element's import property.

index.html

var link = document.querySelector('link[rel="import"]');
link.addEventListener('load', function(e) {
  var importedDoc = link.import;
  // importedDoc points to the document under component.html
});

To obtain the document object from within component.html itself, refer to document.currentScript.ownerDocument.

component.html

var mainDoc = document.currentScript.ownerDocument;
// mainDoc points to the document under component.html

If you are using webcomponents.js, use document._currentScript instead of document.currentScript. The underscore is used to polyfill the currentScript property which is not available in all browsers.

component.html

var mainDoc = document._currentScript.ownerDocument;
// mainDoc points to the document under component.html

By writing the following code at the beginning of your script, you can easily access component.html's document object regardless of if the browser supports HTML Imports or not.

document._currentScript = document._currentScript || document.currentScript;

Performance consideration

One of the benefits of using HTML Imports is to be able to organize resources. But this also means more overhead when loading those resources because of additional HTML file. There are couple of points to consider:

Resolving dependencies

What if multiple imported documents all depend on, and try to load the same library? For example:

Say you are loading jQuery in two imported HTML files. If each import contains a script tag to load jQuery, it will be loaded and executed twice.

index.html

<link rel="import" href="component1.html">
<link rel="import" href="component2.html">

component1.html

<script src="js/jquery.js"></script>

component2.html

<script src="js/jquery.js"></script>

This is a problem imports solve for free.

Unlike script tags, HTML Imports skip loading and executing HTML files that are previously loaded. Taking the previous code as an example, by wrapping the script tag that loads jQuery with an HTML Import, it will be loaded and executed only once.

Dependency resolution

But here's another problem: we have added one more file to load. What can we do with this bloating number of files?

Luckily, we have a tool called "vulcanize" for the solution.

Aggregating network requests

Vulcanize is a tool to aggregate multiple HTML files into one, in order to reduce the number of network connections. You can install it via npm, and use it from the command line. There are grunt and gulp tasks as well so you can make vulcanize part of your build process.

To resolve dependencies and aggregate files in index.html:

$ vulcanize -o vulcanized.html index.html

By executing this command, dependencies in index.html will be resolved and will generate an aggregated HTML file called vulcanized.html.

Learn more about vulcanize here.

Note: http2's server push abilities are considered to eliminate needs for concatenating and vulcanizing files in the future.

Combining HTML Imports with Template, Shadow DOM and Custom Elements

Let's utilize HTML Imports with the code we've been working through this article series.

In case you haven't read the previous articles: With templates, defining the content of your custom element can be declarative. With Shadow DOM, styles, IDs and classes of an element can be scoped to itself. With Custom Elements, you can define your own custom HTML tags.

By combining these with HTML Imports, your custom web component will gain modularity and reusability. Anyone will be able to use it just by adding a link tag.

x-component.html

<template id="template">
  <style>
    ...
  </style>
  <div id="container">
    <img class="webcomponents" src="http://webcomponents.org/img/logo.svg">
    <content select="h1"></content>
  </div>
</template>
<script>
  // This element will be registered to index.html
  // Because `document` here means the one in index.html
  var XComponent = document.registerElement('x-component', {
    prototype: Object.create(HTMLElement.prototype, {
      createdCallback: {
        value: function() {
          var root = this.createShadowRoot();
          var template = document.querySelector('#template');
          var clone = document.importNode(template.content, true);
          root.appendChild(clone);
        }
      }
    })
  });
</script>

index.html

  ...
  <link rel="import" href="x-component.html">
</head>
<body>
  <x-component>
    <h1>This is Custom Element</h1>
  </x-component>
  ...

Notice that because the document object in x-component.html is the same one in index.html, you don't have to write anything tricky. It registers itself for you.

Supported browsers

HTML Imports are supported by Chrome and Opera. Firefox supports it behind a flag as of December 2014 (Update: Mozilla has said they are not currently planning to ship Imports, citing the need to first see how ES6 modules play out).

To check availability, go to chromestatus.com or caniuse.com. For polyfilling other browsers, you can use webcomponents.js (renamed from platform.js).

Resources

So that's the HTML Imports. If you are interested in learning more about the HTML Imports, head over to:

Databound, Typist

Alex Young (DailyJS) @ London › England Monday January 05, 2015 @ 00:00 • over a year ago

Databound

Databound

If you use Ruby on Rails, then you might like this Rails REST library wrapped: Databound (GitHub: Nedomas/databound, License: MIT, npm: databound, Bower: databound) by Domas Bitvinskas. The API looks a bit like the Rails syntax for database models:

User = new Databound('/users')

User.where({ name: 'John' }).then(function(users) {
  alert('Users called John');
});

User.find(15).then(function(user) {
  print('User no. 15: ' + user.name);
});

User.create({ name: 'Peter' }).then(function(user) {
  print('I am ' + user.name + ' from database');
});

Install it with npm, Bower, or as part of a Rails asset pipeline. The author also notes that you can use it with Angular as an alternative to ngResource.

Typist

Typist (GitHub: positionly/Typist, License: MIT, Bower: Typist) by Oskar Krawczyk is a small library for animating text as if it’s being typed. It can work with responsive layouts, and the author claims it has improved click-through-rates on a commercial homepage.

It doesn’t have any dependencies, and is invoked by a constructor that accepts options for the animation intervals. The required markup should specify the text to be typed in the data-typist and data-typist-suffix attributes.

Curl Converter, aja.js, sneakpeek

Alex Young (DailyJS) @ London › England Friday January 02, 2015 @ 00:00 • over a year ago

Curl Converter

Chrome’s “Copy as cURL” menu item is useful, but what if you want to duplicate the same request with Node? Curl Converter (GitHub: NickCarneiro/curlconverter, License: MIT, npm: curlconverter) by Nick Carneiro can convert between cURL syntax and Node’s popular request module. It also supports Python, and can be installed with npm.

aja.js

aja.js (Bower: aja, npm: aja, License: MIT) by Bertrand Chevrier is an Ajax library that supports JSON and JSONP. It can be used to load large chunks of HTML or JSON, and can be installed with npm or Bower.

The API is fluent, so it can be used as a REST client like this:

aja()
  .method('GET')
  .url('/api/customer')
  .data({ firstname: 'John Romuald' })
  .on('200', function(response) {})
  .go();

It also supports some DOM manipulation:

aja()
  .url('/views/page.html')
  .into('.container')
  .go();

It comes with tests that can be run with Grunt, and the readme has more examples for things like posting data.

sneakpeek

If you’re looking for a library to hide the header when the page is scrolled, then sneakpeek (GitHub: antris/sneakpeek, License: MIT, npm: sneakpeek) is nice because it’s small, installable with npm, and has no external dependencies.

It’s a bit like headroom.js, but easier to use with Browserify.

Node Roundup: nchat, hulken, cult

Alex Young (DailyJS) @ London › England Thursday January 01, 2015 @ 00:00 • over a year ago

nchat

nchat (GitHub: irrationalistic/nchat, npm: nchat) by Chris Rolfs is a terminal-based chat application that uses WebSocket, which means it’s easier to use on networks where IRC might be blocked.

Notifications are supported on Mac OS X, and the client can run as the server so you only need to install nchat itself. It supports a few IRC-style commands, like /users, and you can deploy it to hosting providers like Heroku.

hulken

Hulken (GitHub: hulken, License: MIT, npm: hulken) by Johan Hellgren is a stress testing tool for HTTP services. It can make GET and POST requests, and can be configured to send dynamic payloads.

You can use hulken as a command-line tool, or a Node module. The documentation includes all of the supported options, and you’ll need to write an options.json file to use it on the command-line.

cult

Cult (GitHub: typicode/cult, License: MIT, npm: cult) is a tool that monitors changes to a gulpfile and then reloads Gulp. You can run it on the command-line, and it uses the chalk library for pretty output. The readme has an example for supporting gulpfiles that are split across multiple files.

A new Microsoft browser?

Peter-Paul Koch (Quirks Blog) @ Amsterdam › Netherlands Wednesday December 31, 2014 @ 13:02 • over a year ago

Recently the news broke that Microsoft may be working on another browser instead of IE. After reviewing the available evidence I’ve come to the conclusion that, although Microsoft is making a few adjustments, and a name change for IE might be a good idea, the new browser will essentially be IE12. Still, I think we web developers should support the “new browser” narrative.

It seems the decision was taken to fork Trident, Microsoft’s rendering engine. One version will essentially be IE11 with all backward-compatible bells and whistles, while the other one will be IE12, although it may carry a different name and will sport a new interface and support extensions. (IE extensions, that is. Not Chrome or Firefox extensions.)

The idea seems to be that Windows 10 will ship both these browsers. The Internet icon on the desktop will start up IE12, while “if a page calls for IE to render in a compatibility mode” IE11 will be started up. I am assuming that what’s meant here is the meta versioning switch.

Remember that to this day IE11 also contains IE 10, 9, 8, 7, and 5.5, which are accessible through the once-maligned but now mostly-forgotten meta versioning switch, as well as, in the case of 5.5, the good old doctype switch.

The plan seems to be that the new IE12 will not carry all that cruft, but be a forward-looking modern browser. If you need legacy stuff you must start up another browser. Actually this is not such a bad idea. The versioning switch never really caught on on the public Internet (although corporate Intranets may be a different story), so why weigh IE down with a lot of other rendering engines that hardly anyone outside a corporate environment will ever need?

An implication of forking IE is that the new IE11 would be maintained separately from IE12. That might be interesting, although it’s also a lot of hassle for Microsoft. We’ll have to see if they’re really going to maintain two browsers.

Finally, IE may be changing names in the near future. Actually, that’s a pretty good idea. The brand “IE” has become synonymous with slow, old-fashioned, non-standard-compliant browsing — even though from IE10 on there was little reason for that judgement. But IE is being weighed down by the IE6 legacy, and a new name may be just what it needs. So let’s do it. (But not “Spartan,” please. It doesn’t make sense for a browser. Why not an explorer from the good old days? Maybe even a Dutch one?)

Internally, when talking to other web devs, you should treat the next Microsoft browser as IE12. Externally, however, when talking to clients and other non-techies, it could make sense to support the “Microsoft is creating a new browser” narrative. Who knows, your clients or other contacts may decide it’s time to say goodbye to their old IE versions and embrace the new browser. That would help them, us, and Microsoft at the same time.

JavaScript: 2014 in Review

Alex Young (DailyJS) @ London › England Wednesday December 31, 2014 @ 00:00 • over a year ago

I can’t keep up with the libraries that people send to DailyJS – there are just too many! I’ve always felt like this is a good thing: it’s a sign the community is creative and works hard to solve problems in interesting new ways.

It’s hard to decide on a framework or library for a particular task: should you use Koa, Express, or Hapi on the server? Gulp or Grunt as a build system? Then there’s client-side development, with its rich set of libraries. This year alone I’ve used React, Angular, Knockout, and Backbone.

One of the reasons there are so many Node modules is npm is so good. There’s still room for improvement, and the npm blog has been useful for tracking new and upcoming changes to the package manager. It seems like more people than ever are using npm for client-side development as well, so it’ll be interesting to see if Bower still occupies its niche in 2015.

Speaking of 2015, I expect to see more people using ES6 features. We’ve already seen several libraries that use generators to make synchronous-style APIs for client-side modules, and server-side databases. Generators seem hard to learn so it’ll take a while for these APIs to catch on.

There’s still scepticism and even irritation in the Node community about ES6 modules. We’ve spent years writing CommonJS modules and happen to like the syntax, so ES6 modules are a hard pill to swallow. There’s a gist from 2013 about Node and ES6 modules that has comments from well-known Node programmers, and since then es6-module-loader by Guy Bedford has appeared. This library is a polyfill that provides System.import for loading ES6 modules. Guy wrote a great article, Practical Workflows for ES6 Modules with lots of details on ES6 modules from a Node programmer’s perspective.

I don’t think 2015 will see a big Node/ES6 module controversy, though. It seems like CommonJS modules are here to stay, and perhaps eventually we’ll start using both formats.

Another potential controversy is the future of Node forks. io.js got a of initial attention, but it seems to have cooled off over the last fortnight. But I think forks are positive and I’m excited to see what people do with alternative takes on Node.

If you do anything in 2015, please make more libraries and frameworks. We don’t want a totalitarian open source community, we want a big wonderful mess, because open source is an ongoing conversation with no truly right solutions.

React-Grid-Layout

Samuel Reed sent in React-Grid-Layout (GitHub: strml/react-grid-layout, License: MIT), a grid system that is responsive. It requires React but doesn’t require any other library (including jQuery).

You can use the ReactGridLayout custom element in templates which allows you to cleanly specify how many rows and columns you’d like. It also supports props for columns, rows, responsive breakpoints, and layout change events.

Although the author states it has fewer features than Packery or Gridster, it supports some cool stuff like vertical auto-packing and dragging and resizing.

Angular Debug Bar and Reading Position Indicator

Maciej Rzepiński sent in two useful Angular projects:

angular-debug-bar allows you to including a new element, angular-debug-bar, to show some statistics about the current page. This includes a count of $watch and $listener items, DOM objects, and page load time. Each metric is defined with a registerPlugin method, so you might be able to add new metrics although I haven’t tried that myself.

angular-rpi is based on the Reading Position Indicator post from CSS-Tricks. It shows a bar at the top of the page as you scroll the document:

RPI

You can use it with the rpi directive. Both projects have a demo that you can run locally. If you want to edit the progress bar styles, then you can use the .scss file and run npm install ; bower install ; gulp.

ngKookies, preCode.js

Alex Young (DailyJS) @ London › England Monday December 29, 2014 @ 00:00 • over a year ago

ngKookies

ngKookies (GitHub: voronianski/ngKookies, License: MIT, npm: ngkookies) by Dmitri Voronianski is a replacement for the Angular $cookieStore provider. It’s a port of jquery-cookie that helps work around angular.js issue 950.

After loading it, you can set cookies with $kookies.set('name', 'value') and read them with $kookies.get. You can also delete cookies with $kookies.remove.

Each method accepts an options object that can include the path and expires arguments. You can also store JSON objects as cookies with $kookiesProvider.config.json = true.

preCode.js

Have you ever written a blog engine or CMS that has to display source code? If so you’ve probably run into the issue where human-readable HTML doesn’t work well with pre elements if initial indentation is included.

preCode.js (License: MIT) Leon Sorokin is a small script that finds <pre><code> blocks and strips the leading and proceeding whitespace, so syntax highlighters should be able to display code properly.

It’s written using the standard DOM API, so it shouldn’t need any dependencies. It’ll also fix whitespace in textarea as well.

Symbols are a new primitive type in ECMAScript 6 [1]. This blog post explains how they work.

A new primitive type

ECMAScript 6 introduces a new primitive type: symbols. They are tokens that serve as unique IDs. You create symbols via the factory function Symbol() (which is loosely similar to String returning strings if called as a function):

    let symbol1 = Symbol();

Symbol() has an optional string-valued parameter that lets you give the newly created symbol a description:

    > let symbol2 = Symbol('symbol2');
    > String(symbol2)
    'Symbol(symbol2)'

Every symbol returned by Symbol() is unique, every symbol has its own identity:

    > symbol1 === symbol2
    false

You can see that symbols are primitive if you apply the typeof operator to one of them – it will return a new symbol-specific result:

    > typeof symbol1
    'symbol'

Aside: Two quick ideas of mine. If a symbol has no description, JavaScript engines could use the name of the variable (or property) that a symbol is assigned to. Minifiers could also help, by turning the original name of a variable into a parameter for Symbol.

Symbols as property keys

Symbols can be used as property keys:

    const MY_KEY = Symbol();
    let obj = {};
    
    obj[MY_KEY] = 123;
    console.log(obj[MY_KEY]); // 123

Classes and object literals have a feature called computed property keys [2]: You can specify the key of a property via an expression, by putting it in square brackets. In the following object literal, we use a computed property key to make the value of MY_KEY the key of a property.

    const MY_KEY = Symbol();
    let obj = {
        [MY_KEY]: 123
    };

A method definition can also have a computed key:

    const FOO = Symbol();
    let obj = {
        [FOO]() {
            return 'bar';
        }
    };
    console.log(obj[FOO]()); // bar

Enumerating own property keys

Given that there is now a new kind of value that can become the key of a property, the following terminology is used for ECMAScript 6:

  • Property keys are either strings or symbols.
  • Property names are strings.

Let’s examine the API for enumerating own property keys by first creating an object.

    let obj = {
        [Symbol('my_key')]: 1,
        enum: 2,
        nonEnum: 3
    };
    Object.defineProperty(obj,
        'nonEnum', { enumerable: false });

Object.getOwnPropertyNames() ignores symbol-valued property keys:

    > Object.getOwnPropertyNames(obj)
    ['enum', 'nonEnum']

Object.getOwnPropertySymbols() ignores string-valued property keys:

    > Object.getOwnPropertySymbols(obj)
    [Symbol(my_key)]

Reflect.ownKeys() considers all kinds of keys:

    > Reflect.ownKeys(obj)
    [Symbol(my_key), 'enum', 'nonEnum']

The name of Object.keys() doesn’t really work, anymore: it only considers enumerable property keys that are strings.

    > Object.keys(obj)
    ['enum']

Using symbols to represent concepts

In ECMAScript 5, one often represents concepts (think enum constants) via strings. For example:

    var COLOR_RED    = 'RED';
    var COLOR_ORANGE = 'ORANGE';
    var COLOR_YELLOW = 'YELLOW';
    var COLOR_GREEN  = 'GREEN';
    var COLOR_BLUE   = 'BLUE';
    var COLOR_VIOLET = 'VIOLET';

However, strings are not as unique as we’d like them to be. To see why, let’s look at the following function.

    function getComplement(color) {
        switch (color) {
            case COLOR_RED:
                return COLOR_GREEN;
            case COLOR_ORANGE:
                return COLOR_BLUE;
            case COLOR_YELLOW:
                return COLOR_VIOLET;
            case COLOR_GREEN:
                return COLOR_RED;
            case COLOR_BLUE:
                return COLOR_ORANGE;
            case COLOR_VIOLET:
                return COLOR_YELLOW;
            default:
                throw new Exception('Unknown color: '+color);
        }
    }

It is noteworthy that you can use arbitrary expressions as switch cases, you are not limited in any way. For example:

    function isThree(x) {
        switch (x) {
            case 1 + 1 + 1:
                return true;
            default:
                return false;
        }
    }

We use the flexibility that switch offers us and refer to the colors via our constants (COLOR_RED etc.) instead of hard-coding them ('RED' etc.).

Interestingly, even though we do so, there can still be mix-ups. For example, someone may define a constant for a mood:

    var MOOD_BLUE = 'BLUE';

Now the value of BLUE is not unique anymore and MOOD_BLUE can be mistaken for it. If you use it as a parameter for getComplement(), it returns 'ORANGE' where it should throw an exception.

Let’s use symbols to fix this example. Now we can also use the ECMAScript 6 feature const, which lets us declare actual constants (you can’t change what value is bound to a constant, but the value itself may be mutable).

    const COLOR_RED    = Symbol();
    const COLOR_ORANGE = Symbol();
    const COLOR_YELLOW = Symbol();
    const COLOR_GREEN  = Symbol();
    const COLOR_BLUE   = Symbol();
    const COLOR_VIOLET = Symbol();

Each value returned by Symbol is unique, which is why no other value can be mistaken for BLUEnow. Intriguingly, the code of getComplement() doesn’t change at all if we use symbols instead of strings, which shows how similar they are.

Symbols as keys of properties

Being able to create properties whose keys never clash with other keys is useful in two situations:

  • If several parties contribute internal properties to the same object, via mixins.
  • To keep meta-level properties from clashing with base-level properties.

Symbols as keys of internal properties

Mixins are object fragments (sets of methods) that you can compose to augment the functionality of an object or a prototype. If their methods have symbols as keys, they can’t clash with other methods (of other mixins or of the object that they are added to), anymore.

Public methods are seen by clients of the object a mixin is added to. For usability’s sake, you probably want those methods to have string keys. Internal methods are only known to the mixin or only needed to communicate with it. They profit from having symbols as keys.

Symbols do not offer real privacy, because it is easy to find out the symbol-valued property keys of an object. But the guarantee that a property key can’t ever clash with any other property key is often enough. If you truly want to prevent the outside from accessing private data, you need to use WeakMaps or closures. For example:

    // One WeakMap per private property
    const PASSWORD = new WeakMap();
    class Login {
        constructor(name, password) {
            this.name = name;
            PASSWORD.set(this, password);
        }
        hasPassword(pw) {
            return PASSWORD.get(this) === pw;
        }
    }

The instances of Login are keys in the WeakMap PASSWORD. The WeakMap does not prevent the instances from being garbage-collected. Entries whose keys are objects that don’t exist anymore are removed from WeakMaps.

The same code looks as follows if you use a symbol key for the internal property.

    const PASSWORD = Symbol();
    class Login {
        constructor(name, password) {
            this.name = name;
            this[PASSWORD] = password;
        }
        hasPassword(pw) {
            return this[PASSWORD] === pw;
        }
    }

Symbols as keys of meta-level properties

Symbols having unique identities makes them ideal as keys of public properties that exist on a different level than “normal” property keys, because meta-level keys and normal keys must not clash. One example of meta-level properties are methods that objects can implement to customize how they are treated by a library. Using symbol keys protect the library from mistaking normal methods as customization methods.

Iterability [3] in ECMAScript 6 is one such customization. An object is iterable if it has a method whose key is the symbol (stored in) Symbol.iterator. In the following code, obj is iterable.

    let obj = {
        data: [ 'hello', 'world' ],
        [Symbol.iterator]() {
            const self = this;
            let index = 0;
            return {
                next() {
                    if (index < self.data.length) {
                        return {
                            value: self.data[index++]
                        };
                    } else {
                        return { done: true };
                    }
                }
            };
        }
    };

The iterability of obj enables you to use the for-of loop and similar JavaScript features:

    for (let x of obj) {
        console.log(x);
    }

Crossing realms with symbols

A code realm (short: realm) is a context in which pieces of code exist. It includes global variables, loaded modules and more. Even though code exists “inside” exactly one realm, it may have access to code in other realms. For example, each frame in a browser has its own realm. And execution can jump from one frame to another, as the following HTML demonstrates.

    <head>
        <script>
            function test(arr) {
                var iframe = frames[0];
                // This code and the iframe’s code exist in
                // different realms. Therefore, global variables
                // such as Array are different:
                console.log(Array === iframe.Array); // false
                console.log(arr instanceof Array); // false
                console.log(arr instanceof iframe.Array); // true
    
                // But: symbols are the same
                console.log(Symbol.iterator ===
                            iframe.Symbol.iterator); // true
            }
        </script>
    </head>
    <body>
        <iframe srcdoc="<script>window.parent.test([])</script>">
    </iframe>
    </body>

The problem is that each realm has its own local copy of Array and, because objects have individual identities, those local copies are considered different, even though they are essentially the same object. Similarly, libraries and user code a loaded once per realm and each realm has a different version of the same object.

In contrast, members of the primitive types boolean, number and string don’t have individual identities and multiple copies of the same value are not a problem: The copies are compared “by value” (by looking at the content, not at the identity) and are considered equal.

Symbols have individual identities and thus don’t travel across realms as smoothly as other primitive values. That is a problem for symbols such as Symbol.iterator that should work across realms: If an object is iterable in one realm, it should be iterable in others, too. If a cross-realm symbol is provided by the JavaScript engine, the engine can make sure that the same value is used in each realm. For libraries, however, we need extra support, which comes in the form of the global symbol registry: This registry is global to all realms and maps strings to symbols. For each symbol, libraries need to come up with a string that is as unique as possible. To create the symbol, they don’t use Symbol(), they ask the registry for the symbol that the string is mapped to. If the registry already has an entry for the string, the associated symbol is returned. Otherwise, entry and symbol are created first.

You ask the registry for a symbol via Symbol.for() and retrieve the string associated with a symbol (its key) via Symbol.keyFor():

    > let sym = Symbol.for('Hello everybody!');
    > Symbol.keyFor(sym)
    'Hello everybody!'

As expected, cross-realm symbols, such as Symbol.iterator, that are provided by the JavaScript engine are not in the registry:

    > Symbol.keyFor(Symbol.iterator)
    undefined

Safety checks

JavaScript warns you about two mistakes by throwing exceptions: Invoking Symbol as a constructor and coercing symbols to string.

Invoking Symbol as a constructor

While all other primitive values have literals, you need to create symbols by function-calling Symbol. Thus, it is relatively easy to accidentally invoke Symbol as a constructor. That produces instances of Symbol and is not very useful. Therefore, an exception is thrown when you try to do that:

    > new Symbol()
    TypeError: Symbol is not a constructor

There is still a way to create wrapper objects, instances of Symbol: Object, called as a function, converts all values to objects, including symbols.

    > let sym = Symbol();
    > typeof sym
    'symbol'
    
    > let wrapper = Object(sym);
    > typeof wrapper
    'object'
    > wrapper instanceof Symbol
    true

Coercing a symbol to string

Given that both strings and symbols can be property keys, you want to protect people from accidentally converting a symbol to a string. For example, like this:

    let propertyKey = '__' + anotherPropertyKey;

ECMAScript 6 throws an exception if one uses implicit conversion to string (handled internally via the ToString operation):

    > var sym = Symbol('My symbol');
    > '' + sym
    TypeError: Cannot convert a Symbol value to a string

However, you can still explicitly convert symbols to strings:

    > String(sym)
    'Symbol(My symbol)'
    > sym.toString()
    'Symbol(My symbol)'

Frequently asked questions

Are symbols primitives or objects?

In some ways, symbols are like primitive values, in other ways, they are like objects:

  • Symbols are like strings (primitive values) w.r.t. what they are used for: as representations of concepts and as property keys.
  • Symbols are like objects in that each symbol has its own identity.

The latter point can be illustrated by using objects as colors instead of symbols:

    const COLOR_RED = Object.freeze({});
    ···

Optionally, you can make objects-as-symbols more minimal by freezing Object.create(null) instead of {}. Note that, in contrast to strings, objects can’t become property keys.

What are symbols then – primitive values or objects? In the end, they were turned into primitives, for two reasons.

First, symbols are more like strings than like objects: They are a fundamental value of the language, they are immutable and they can be used as property keys. Symbols having unique identities doesn’t necessarily contradict them being like strings: UUID algorithms produce strings that are quasi-unique.

Second, symbols are most often used as property keys, so it makes sense to optimize the JavaScript specification and the implementations for that use case. Then many abilities of objects are unnecessary:

  • Objects can become prototypes of other objects.
  • Wrapping an object with a proxy doesn’t change what it can be used for.
  • Objects can be introspected: via instanceof, Object.keys(), etc.

Them not having these abilities makes life easier for the specification and the implementations. There are also reports from the V8 team that when handling property keys, it is simpler to treat a primitive type differently than objects.

Aren’t strings enough?

In contrast to strings, symbols are unique and prevent name clashes. That is nice to have for tokens such as colors, but it is essential for supporting meta-level methods such as the one whose key is Symbol.iterator. Python uses the special name __iter__ to avoid clashes. You can reserve double underscore names for programming language mechanisms, but what is a library to do? With symbols, we have an extensibility mechanism that works for everyone. As you can see later, in the section on public symbols, JavaScript itself already makes ample use of this mechanism.

There is one hypothetical alternative to symbols when it comes to clash-free property keys: use a naming convention. For example, strings with URLs (e.g. 'http://example.com/iterator'). But that would introduce a second category of property keys (versus “normal” property names that are usually valid identifiers and don’t contain colons, slashes, dots, etc.), which is basically what symbols are, anyway. Then it is more elegant to explicitly turn those keys into a different kind of value.

The symbol API

This section gives an overview of the ECMAScript 6 API for symbols.

The function Symbol

  • Symbol(description?)symbol
    Creates a new symbol. The optional parameter description allows you to give the symbol a description, which is useful for debugging.

Symbol is not intended to be used as a constructor – an exception is thrown if you invoke it via new.

Public symbols

Several public symbols can be accessed via properties of Symbol. They are all used as property keys and enable you to customize how JavaScript handles an object.

Customizing basic language operations:

  • Symbol.hasInstance (method)
    Lets an object O customize the behavior of x instanceof O.

  • Symbol.toPrimitive (method)
    Lets an object customize how it is converted to a primitive value. This is the first step whenever something is coerced to a primitive type (via operators etc.).

  • Symbol.toStringTag (string)
    Called by Object.prototype.toString to compute the default string description of an object obj: '[object '+obj[Symbol.toStringTag]+']'.

Iteration [3]:

  • Symbol.iterator (method)
    Makes an object iterable. Returns an iterator.

Regular expressions: Four string methods are simply forwarded to their regular expression parameters. The methods that they are forwarded to have the following keys.

  • Symbol.match is used by String.prototype.match.
  • Symbol.replace is used by String.prototype.replace.
  • Symbol.search is used by String.prototype.search.
  • Symbol.split is used by String.prototype.split.

Miscellaneous:

  • Symbol.unscopables (Object)
    Lets an object hide some properties from the with statement.

  • Symbol.species (method)
    Helps with cloning typed arrays and instances of RegExp, ArrayBuffer and Promise.

  • Symbol.isConcatSpreadable (boolean) Indicates whether Array.prototype.concat should concatenate the elements of an object or the object as an element.

Global symbol registry

If you want a symbol to be the same in all realms, you need to create it via the global symbol registry. The following method lets you do that:

  • Symbol.for(str)symbol
    Returns the symbol whose key is the string str in the registry. If str isn’t in the registry yet, a new symbol is created and filed in the registry under the key str.

Another method lets you make the reverse look up and found out under which key a string is stored in the registry. This is may be useful for serializing symbols.

  • Symbol.keyFor(sym)string
    returns the string that is associated with the symbol sym in the registry. If sym isn’t in the registry, this method returns undefined.

Further reading

  1. Using ECMAScript 6 today
  2. ECMAScript 6: new OOP features besides classes
  3. Iterators and generators in ECMAScript 6

Dynamic-json-resume, JSnoX

Alex Young (DailyJS) @ London › England Friday December 26, 2014 @ 00:00 • over a year ago

Dynamic-json-resume

I don’t know about you, but I hate putting together my résumé. I start to focus too much on the presentation even though you’re meant to keep it simple. Dynamic-json-resume (GitHub: jrm2k6/dynamic-json-resume, License: MIT, npm: json-resume-dynamic) by Jeremy Dagorn is a module for generating résumés from a simple JSON format. You can output PDFs, and use it with a Node application.

Because your CV is now represented by a structured data format, you can reuse it in other places. For example, your personal website could render it in a sidebar.

James Long’s article, Removing User Interface Complexity, or Why React is Awesome, inspired the project. React seems like the perfect way to manipulate and render your JSON CV.

JSnoX

What do you do if you like React but dislike JSX? Shawn Price sent in his coworker’s project, JSnoX (GitHub: af/JSnoX, License: MIT, npm: jsnox), which provides a simple React markup API that works in pure JavaScript:

var d = require('jsnox')(React)
var LoginForm = React.createClass({
  submitLogin: function() { ... },

  render: function() {
    return d('form[method=POST]', { onSubmit: this.submitLogin }, [
      d('h1.form-header', 'Login'),
      d('input:email[name=email]', { placeholder: 'Email' }),
      d('input:password[name=pass]', { placeholder: 'Password' }),
      d(MyOtherComponent, { myProp: 'foo' }),
      d('button:submit', 'Login')
    ]);
  }
});

This API sidesteps the issue of JavaScript’s lack of multiline string handling for embedded templates, while not requiring too much fiddly syntax for handling DOM attributes.

Holiday Hacking: Apps

Alex Young (DailyJS) @ London › England Thursday December 25, 2014 @ 00:00 • over a year ago

What do you do when you leave your computer/laptop at home while you visit family for the holidays? I always do this, thinking that it’ll be better to spend some quality time with the family, but there are moments where people are doing their own thing and I wish I had a laptop to play with some code.

These days of course many of us tote around tablets or large phones, so there is some potential for hacking or at least learning about new programming techniques. One of my favourite apps is actually Vim, which you can get for iOS and Android:

To the uninitiated, Vim for a touchscreen sounds horrible, but it’s actually pretty good – because it’s modal you can enter Command-line mode with : and leave with the escape key easily enough. If you’re an experienced Vim user then it can be revealing to think about the mnemonics for commands rather than relying on muscle memory.

I also found that the big programming video services have iOS and Android apps, so you can study a new programming language, framework, or library:

I’ve actually used the Pluralsight app on Android during my commute to help me learn enough C# to implement the Windows portion of a Node/Windows/iOS/Mac application I work on professionally.

Because tablet operating systems support browsers, then there are a lot of apps that wrap the built-in JavaScript interpreter to allow you to practice writing JavaScript. For example:

And you can even write Node on iOS with Node - JavaScript Interpreter. There are manuals for Node on the Play Store as well. Or you can get a more broad manual management app like Dash. I found Dash useful for looking up Mozilla’s JavaScript documentation, and Node’s, when I was working offline on my Node book.

Apple and Google’s book stores also sell many technical books from the popular computer science book publishers, so you should be able to find something to do while your parents argue and your partner is walking the dog, wrangling toddlers, or snoozing after too much turkey.

Node Roundup: 0.10.35, Prettiest, Artisan Validator

Alex Young (DailyJS) @ London › England Wednesday December 24, 2014 @ 00:00 • over a year ago

Node 0.10.35

Node 0.10.35 was released today, which has some changes to timers relating to the unref behaviour:

  • timers: don’t close interval timers when unrefd (Julien Gilli)
  • timers: don’t mutate unref list while iterating it (Julien Gilli)

This was released soon after 0.10.34, which updated v8, uv, zlib, and some core modules including child_process and crypto.

Prettiest

What if you want to prevent a command-line script from executing more than once? Prettiest (GitHub: punkave/prettiest, License: MIT, npm: prettiest) from P’unk Avenue LLC combines data storage and locking, and should work well for Node command-line scripts made with modules like ShellJS.

This is the simplest example – it will track how many times it has been run:

var data = require('prettiest')();

data.count = data.count || 0;
data.count++;
console.log('I have been run', data.count, ' times.');

I’ve often wanted to persist data in command-line scripts, but didn’t want to bother with sqlite or JSON file serialisation, so this seems ideal for such cases. And even if you want the locking behaviour, your scripts can still be asynchronous.

Artisan Validator

Connor Peet is on a quest to create a simple and well-documented data validator for Node. Artisan Validator (GitHub: MCProHosting/artisan-validator, License: MIT, npm: artisan-validator) allows you to define rules that get validated against objects, so you can easily hook it into a Node web application:

var validator = require('artisan-validator')();
var rules = {
  username: ['required', 'between: 4, 30', 'alphanumeric'],
  password: ['required', 'longer: 5'],
  acceptTOS: ['required', 'boolean: true']
};

validator.try(req.body, rules).then(function (result) {
  if (result.failed) {
    res.json(400, result.errors);
  } else {
    registerAccount();
  }
});

You can add custom validators with validator.validators.add, but there are quite a few built-in rules that cover JavaScript types, and various string and date formats. The error messages can be localised as well.

Particle Paintings, AMD to CommonJS with Recast

Alex Young (DailyJS) @ London › England Tuesday December 23, 2014 @ 00:00 • over a year ago

Particture

Particture

Tadeu Zagallo sent in a Canvas experiment that uses typed arrays, optimised sorting algorithms, and inlining and bitwise operators to boost performance. The Particture demo allows you to use your webcam for the source image, and draws images with a cool trail effect.

The repository at tadeuzagallo/particture has the source, and it uses dat.gui for the controls.

Recast

Many readers seem to be searching for solutions to the module refactor problem, where older projects are refactored to use modern module systems. Dustan Kasten wanted to convert projects that use AMD to CommonJS, and he’s used Recast to do this, through the recast-to-cjs project that is published by his company (Skookum Digital Works).

Dustan has written an article that shows how to convert a project to CommonJS: Converting a project from AMD to CJS with Recast. The AST is traversed to find AMD definitions, and then converted into equivalent CommonJS dependencies.

It’s possible that Node developers may end up doing something like this if ES6 modules become the norm, although I suspect ES6’s export and import statements will need manual intervention to take advantage of import obj from lib.

Classes [2] are the major new OOP feature in ECMAScript 6 [1]. However, it also includes new features for object literals and new utility methods in Object. This blog post describes them.

New features of object literals

Method definitions

In ECMAScript 5, methods are properties whose values are functions:

    var obj = {
        myMethod: function () {
            ···
        }
    };

In ECMAScript 6, methods are still function-valued properties, but there is now a more compact way of defining them:

    let obj = {
        myMethod() {
            ···
        }
    };

Getters and setters continue to work as they did in ECMAScript 5 (note how syntactically similar they are to method definitions):

    let obj = {
        get foo() {
            console.log('GET foo');
            return 123;
        },
        set bar(value) {
            console.log('SET bar to '+value);
            // return value is ignored
        }
    };

Let’s use obj:

    > obj.foo
    GET foo
    123
    > obj.bar = true
    SET bar to true
    true

There is also a way to concisely define properties whose values are generator functions [3]:

    let obj = {
        * myGeneratorMethod() {
            ···
        }
    };

This code is equivalent to:

    let obj = {
        myGeneratorMethod: function* () {
            ···
        }
    };

Property value shorthands

Property value shorthands let you abbreviate the definition of a property in an object literal: If the name of the variable that specifies the property value is also the property key then you can omit the key. This looks as follows.

    let x = 4;
    let y = 1;
    let obj = { x, y };

The last line is equivalent to:

    let obj = { x: x, y: y };

Property value shorthands work well together with destructuring [4]:

    let obj = { x: 4, y: 1 };
    let {x,y} = obj;
    console.log(x); // 4
    console.log(y); // 1

One use case for property value shorthands are multiple return values [4].

Computed property keys

Remember that there are two ways of specifying a key when you set a property.

  1. Via a fixed name: obj.foo = true;
  2. Via an expression: obj['b'+'ar'] = 123;

In object literals, you only have option #1 in ECMAScript 5. ECMAScript 6 additionally provides option #2:

    let propKey = 'foo';
    let obj = {
        [propKey]: true,
        ['b'+'ar']: 123
    };

This new syntax can also be combined with a method definition:

    let obj = {
        ['h'+'ello']() {
            return 'hi';
        }
    };
    console.log(obj.hello()); // hi

The main use case for computed property keys are symbols: you can define a public symbol and use it as a special property key that is always unique. One prominent example is the symbol stored in Symbol.iterator. If on object has a method with that key, it becomes iterable [3]. The method must return an iterator, which is used by constructs such as the for-of loop to iterate over the object. The following code demonstrates how that works.

    let obj = {
        * [Symbol.iterator]() { // (A)
            yield 'hello';
            yield 'world';
        }
    };
    for (let x of obj) {
        console.log(x);
    }
    // Output:
    // hello
    // world

Line A starts a generator method definition with a computed key (the symbol stored in Symbol.iterator).

New methods of Object

Object.assign(target, source_1, source_2, ···)

This method merges the sources into the target: It modifies target, first copies all enumerable own properties of source_1 into it, then all own properties of source_2, etc. At the end, it returns the target.

    let obj = { foo: 123 };
    Object.assign(obj, { bar: true });
    console.log(JSON.stringify(obj));
        // {"foo":123,"bar":true}

Let’s look more close at how Object.assign() works:

  • Both kinds of property keys: Object.assign() supports both strings and symbols as property keys.

  • Only enumerable own properties: Object.assign() ignores inherited properties and properties that are not enumerable.

  • Copying via assignment: Properties in the target object are created via assignment (internal operation [[Put]]). That means that if target has (own or inherited) setters, those will be invoked during copying. An alternative would have been to define new properties, an operation which always creates new own properties and never invokes setters. There originally was a proposal for a variant of Object.assign() that uses definition instead of assignment. That proposal has been rejected for ECMAScript 6, but may be reconsidered for later editions.

Use cases for Object.assign()

Let’s look at a few use cases. You can use Object.assign() to add properties to this in a constructor:

    class Point {
        constructor(x, y) {
            Object.assign(this, {x, y});
        }
    }

Object.assign() is also useful for filling in defaults for missing properties. In the following example, we have an object DEFAULTS with default values for properties and an object options with data.

    const DEFAULTS = {
        logLevel: 0,
        outputFormat: 'html'
    };
    function processContent(options) {
        let options = Object.assign({}, DEFAULTS, options); // (A)
        ···
    }

In line A, we created a fresh object, copied the defaults into it and then copied options into it, overriding the defaults. Object.assign() returns the result of these operations, which we assign to options.

Another use case is adding methods to objects:

    Object.assign(SomeClass.prototype, {
        someMethod(arg1, arg2) {
            ···
        },
        anotherMethod() {
            ···
        }
    });

You could also assign functions, but then you don’t have the nice method definition syntax and need to mention SomeClass.prototype each time:

    SomeClass.prototype.someMethod = function (arg1, arg2) {
        ···
    };
    SomeClass.prototype.anotherMethod = function () {
        ···
    };

One last use case for Object.assign() is a quick way of cloning objects:

    function clone(orig) {
        return Object.assign({}, orig);
    }

This way of cloning is also somewhat dirty, because it doesn’t preserve the property attributes of orig. If that is what you need, you have to use property descriptors.

If you want the clone to have the same prototype as the original, you can use Object.getPrototypeOf() and Object.create():

    function clone(orig) {
        let origProto = Object.getPrototypeOf(orig);
        return Object.assign(Object.create(origProto), orig);
    }

Object.getOwnPropertySymbols(obj)

In ECMAScript 6, the key of a property can be either a string or a symbol. There are now five tool methods that retrieve the property keys of an object obj:

  • Object.keys(obj)Array<string>
    retrieves all string-valued keys of all enumerable own properties.

  • Object.getOwnPropertyNames(obj)Array<string>
    retrieves all string-valued keys of all own properties.

  • Object.getOwnPropertySymbols(obj)Array<symbol>
    retrieves all symbol-valued keys of all own properties.

  • Reflect.ownKeys(obj)Array<string|symbol>
    retrieves all keys of all own properties.

  • Reflect.enumerate(obj)Iterator
    retrieves all string-values keys of all enumerable properties.

Object.is(value1, value2)

The strict equals operator (===) treats two values differently than one might expect.

First, NaN is not equal to itself.

    > NaN === NaN
    false

That is unfortunate, because it often prevents us from detecting NaN:

    > [0,NaN,2].indexOf(NaN)
    -1

Second, JavaScript has two zeros, but strict equals treats them as if they were the same value:

    > -0 === +0
    true

Doing this is normally a good thing.

Object.is() provides a way of comparing values that is a bit more precise than ===. It works as follows:

    > Object.is(NaN, NaN)
    true
    > Object.is(-0, +0)
    false

Everything else is compared as with ===.

If we combine Object.is() with the new ECMAScript 6 array method findIndex() [5], we can find NaN in arrays:

    > [0,NaN,2].findIndex(x => Object.is(x, NaN))
    1

Object.setPrototypeOf(obj, proto)

This method sets the prototype of obj to proto. The non-standard way of doing so in ECMAScript 5, that is supported by many engines, is via assinging to the special property __proto__. The recommended way of setting the prototype remains the same as in ECMAScript 5: during the creation of an object, via Object.create(). That will always be faster than first creating an object and then setting its prototype. Obviously, it doesn’t work if you want to change the prototype of an existing object.

References

  1. Using ECMAScript 6 today
  2. ECMAScript 6: classes
  3. Iterators and generators in ECMAScript 6
  4. Multiple return values in ECMAScript 6
  5. ECMAScript 6’s new array methods
pluto/1.3.2 - Ruby/2.0.0 (2014-11-13/x86_64-linux) on Rails/4.2.0 (production)