Javascript has a lot of little WATs lurking in the dark corners of the language.

In my opinion this generally doesn't matter because there aren't very good reasons why you should ever need to tread into that territory to begin with, but I suppose people do, and so:



These things made it into the language because they were released, and then people were confused, and complained, but other people had written code that used it (for some reason), and therefore to fix those bugsfeatures would cause problems.

Backwards compatibility was favoured over linguistic clarity, which is fair enough, I suppose.


Now there's ECMA Script 6, which introduces lots of bugsfeatures all over again.

I stumbled across this one the other day:

Javascript Arrays have a map method, which accepts a function as an argument. Pass in a function and a new Array containing the results of the function call on each will be returned.

var A = [1,2,3];

A.map(function (x) { return x; }); // [1, 2, 3]

Cool. ES6 introduces the arrow syntax for anonymous functions (aka lambdas), which makes it a tiny bit faster to write the same thing.

A.map((x) => x); // [1, 2, 3]

You don't even have to use the initial elements of the array:

A.map(() => 'pew'); // ['pew', 'pew', 'pew']

Now, knowing that, let's play around a little more...

A.map(function () { return {}; }); // [{}, {}, {}]

Cool, an array of objects, let's go do that with ES6

A.map(() => {}) // [undefined, undefined, undefined]


So, the reason for this is pretty simple. In a lot of cases, you can't pull off everything you want to do in a function using only a single block. For this reason, they provided block syntax:

A.map(() => { return {}; }); // [{}, {}, {}] // there it is!

A.map((x) => { var y = x*x; return y; }); // [1, 4, 9]

So there! We recently started using JSHint at my work, and it will complain about a lot of things:

if (true) return true; // NOPE

if (true) { // put it in blocks
    return true;

I hope that in the future it will also be recommended that you put your arrow syntax in blocks, because other objects get totally eaten by the parser.

A.map(() => {pew: 'pew'}); // [undefined, undefined, undefined]


If I'm using the console in my browser, and I don't want to type a lot, I might take shortcuts and not use the block syntax. That being said, I'm still not using arrow syntax in my actual source, because I'm really stubborn, but if I do, you're probably going to see everything in blocks.

I don't know if this is a requirement for JSHint yet, but if it isn't, I expect it will be.

That's all! Happy coding!



NOTE: I've since looked further into this oddness. The results are here