Robert Fisher

Just thinking out loud

EcmaScript idioms

If you register and log in you can add comments to my pages. If viewing the main blog page, click the # underneath an entry to comment on it.

Defaults

This will set y to zero if x is undefined or x if x is defined:

var y = x || 0;

(Be careful when using this idiom with strings.)

This one is kind of weird. I haven't yet seen a case where it is useful. It will (I think) set y to undefined if x is undefined. Otherwise y will be set to 1.

var y = x && 1;

Keyword arguments

Use literal objects for keyword parameters:

keyword_function({foo: my_foo, bar: my_bar});

In

inspiration

function is_vowel(letter)
{
    return letter in { a:1, e:1, i:1, o:1, u:1 };
}

A function that can make constructing sets a bit simpler.

function set()
{
    var result = {};
    for(var i = 0; i < arguments.length; i++)
        result[arguments[i]] = true;
    return result;
}

function is_vowel(letter)
{
    return letter in set('a', 'e', 'i', 'o', 'u');
}

Delay & force

Without macros to create our own special forms, you have to make the λ explicit. So, delay & force don't look as magical as they do in Scheme. (u_u)

Delay:

var promise = function(){ return expression; }

Force:

var value = promise();

Or, if you want to look clever:

function force(promise) { return promise(); }

EcmaScript kludges:

The arguments "array" is not actually an array. Thanks to the dynamic nature of EcmaScript, however, you can make it borrow methods from array!

function returnAllButMyFirstArgument() {
    arguments.slice = Array.prototype.slice;
    return arguments.slice(1);
}

Prefer String.join to +

['<p>', paragraphText, '</p>'].join()

back to Scheme & other programming stuff