02 June 2015

I was happy to meetup with other JavaScripters in Iceland. I was also happy to discuss my latest set of tools which includes Babel (via JSPM) when a discussion topic came up that I thought I had a handle on.

Iterating a NodeList–we all need to do it from time to time. Since I started using tools like virtual-dom and paperclip I just haven’t iterated a NodeList that wasn’t another collection type (e.g., jquery object). This was evident as I opened the Babel REPL and starting throwing things at the problem: for-of, spread operator, and other ideas failed (beer on an empty stomach may or may not have played a role). I still don’t remember what I was doing wrong.

I slept on it and woke up with Array.from which totally works. I read up on some other proposals Babel already supports: Object.entries, Object.values, and a native iterator for NodeList (which is what makes the spread operator work). Now, I have a solution with no problem…

var elms = document.querySelectorAll('a');

//es5 way
Array.prototype.slice.call(elms, 0).map(function (elm) {console.log(elm.href)});

//es6 way(s)
Array.from(elms).map(({href}) => console.log(href));
for (const {href} of elms) console.log(href);
[for ({href} of elms) href].map(href => console.log(href));
[...elms].map(({href}) => console.log(href));

//es7 way(s)
Object.values(elms).map(({href}) => console.log(href));
Object.entries(elms).map(([key, {href}]) => console.log(href));

//(mis?)using the function bind operator
const log = function () {console.log(this)};
Object.values(elms).map(({href}) => href::log());


blog comments powered by Disqus