JavaScript Obscured (How to confuse coworkers)

| | Comments (3) | TrackBacks (0)

I was reading a blog entry at Web Reflection that outlined some obscure solutions to common JavaScript patterns.

I thought that entry was interesting, but I'm not sure I'd use them because of code readability and maintenance. It did get me thinking of some other ways to obscure simple tasks.

a better ternary?

Have a co-worker that thinks ternary expressions are ugly? Offer them this alternative:

var saveFunc = isNew ? insert : update; // becomes... var saveFunc = [update, insert][+isNew];

Looks a little crazy, huh? It works because a '+' or '-' before a boolean converts the boolean to a one or zero depending on its truthiness. The one or zero is accessing that element of the array. They'll be begging for ternary after that.

I think I might actually use that that syntax in situations where I need to add one depending on a boolean:

var version = x + (+shouldIncrement); var version = x + (-shouldNotIncrement);

throw out parseInt

Converting a string to a number is often done with parseInt. There are some gotchas that many people fall into in that the second parameter to parseInt is not required, but should be. For instance:

var x = parseInt("08"); // x is 0, because it assumes octal (base 8) var x = parseInt("08", 10); // force base 10 // x is 8 // an alternative var x = +"08"; // x is 8 // Negation works also var x = -"08"; // x is -8

Use them wisely, or preferably never.

3 Comments

Ternary is interesting for many reason, but I wonder if performances are good enough.

For version, you do not need brackets, while the parseInt alternative does not repsect its functionality is some case like: alert(+"08.2")

In my Stack constructor, I have used the fastest parseInt alternative, that is basically this one:

var toInt = someVar > 1;

Anyway, nice stuff and thanks for the link :-)

P.S. your ternary proposal is still interesting, but about 2 or more times slower than ternary operator


for(var v1 = "value1", v2 = "value2", i = 0, t1 = new Date; i

kangax said:

var saveFunc = isNew ? insert : update;
// and
var saveFunc = [update, insert][+isNew];

are not quite the same. Former converts "isNew" to a boolean, while latter does type coercion (toNumber)

You probably meant:

[update, insert][+(!!isNew)];


Cheers,
kangax

Leave a comment


Type the characters you see in the picture above.

0 TrackBacks

Listed below are links to blogs that reference this entry: JavaScript Obscured (How to confuse coworkers).

TrackBack URL for this entry: http://www.nearinfinity.com/mt/mt-tb.cgi/458