... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)

2012-03-26

JScript vs. Function Expressions

In Javascript, a top-level function expression is not allowed. For example,

function(){return 3;}

will give a syntax error such as Unexpected token (. The work-around is to enclose the expression in parentheses:

(function(){return 3;})

At least, in most environments this is a work-around. In JScript, both expressions are quietly ignored. No error message is given, and no return value results. In JScript, a more elaborate work-around is required:

[function(){return 3;}][0]

or

0?0:function(){return 3;}

... anything that includes the function expression as part of a wider expression will do.

At this point, one might be wondering why anyone would care. What's the use of a top-level expression anyway? In my case, the context was one that used eval. The contents of a Javascript file were being loaded and evaluated where the contract was for the file to contain a single anonymous function expression.

Blog Archive