spacer spacer spacer


Abject expression

Henry and I were looking at the debugger and wondering why:

lzx> function foo () { return 'Fu'; }
«Function#0| foo»
lzx> foo
WARNING: interactive-eval-2:-1: reference to undefined variable 'foo'
lzx> function foo () { return 'Fu'; };
lzx> foo
«Function#2| foo»

In the first case, a function named ‘foo’ is created, but it is not the value of the global foo. Instead the Debug evaluator returns a value which is that function object. In the second case, the evaluator does not return a value, and the global foo is defined to be the function. What gives?

It turns out the debugger evaluator will first try to evaluate what you type as an expression, and if that fails, it will try to evaluate it as a statement. The second form is clearly not an expression (think of what you type as having parens around it — the semi-colon forces the second form to be a statement list, with an empty second statement). It turns out that this is correct ECMA semantics. It is not whether you name a function or not that determines when a global definition will be made; two things must be true: 1) the function must be named, and 2) the function declaration must occur in a statement context. If the function declaration occurs in an expression context, all you have done is to create a named function object as the value of that expression, you have not defined that name as the function… Subtle.

There is a bug in the current debugger, though, because:

lzx> a = 3
lzx> a
WARNING: interactive-eval-7:-1: reference to undefined variable 'a'
lzx> a = 3;
lzx> a

In the case of =, it should not matter whether you are in an expression or statement context. = should cause the side-effect of assignment. Henry and I are looking into fixing that bug.

But in the mean time, if you ever wonder why when you define a function in the debugger it does not take, take a clue from what the evaluator prints out: if it prints out a function object, all you did was create a function, not define a function. Add the semi-colon after your definition and you will define the function (and not see a value printed).

22:01 | Link | Reply | Track