Javascript does not provide full lexical scope

By 8 nic on April 30, 2007

It's not quite lisp.

So this:


var f;
{ var x=10;
f = function () { return x; }
}
var x = 20;
f();

has f() returning 20 when a lisp programmer would expect 10.

To achieve lexical scope is quite easy though, you just do this:


var f;

(function (){
var x=10;
f = function () { return x; }
})();

var x = 20;
f();

In other words, instead of a block you write your scope with anonymous function calls.

It's kinda odd because you'd have thought that given that they had anonymous function calls that's how they would have implemented blocks (as Scheme's (begin ...) for example) but there y'go. Nowt so wierd as netscape.

Embed Claim Make a related claim

Discussion (4)

http://wonko.com/

7 Ryan Grove who disagreed, says

That's kind of a weird way of doing it, but I guess it makes sense to someone with a Lisp background (I don't have a Lisp background).

I prefer Douglas Crockford's method for ensuring lexical scope using closures. It does essentially the same thing, but I think it's a little more clear and maintainable. He describes it in his Advanced JavaScript talk.

That said, since you demonstrated that JavaScript does, in fact, provide full lexical scope (just not in the way you might expect), I have to disagree with this claim. ;)

Or does "full" imply a specific kind of scoping?

Make a related claim about 1 year ago (link)
http://www.tapsellferrier.co.uk/nicferrier/

8 nic who agreed, says

Right Ryan. What do YOU call lexical scope then FFS?

Make a related claim about 1 year ago (link)
http://wonko.com/

7 Ryan Grove who disagreed, says

Please reread my comment. I agree with what I think is your definition of lexical scope, and I agree with your demonstration that JavaScript can be made to provide lexical scope.

As I said, I disagreed with the claim because you claimed that JavaScript doesn't provide lexical scope, then demonstrated that it does, thus disproving your own claim.

You follow?

Make a related claim about 1 year ago (link)
http://www.tapsellferrier.co.uk/nicferrier/

8 nic who agreed, says

"full" implies, well... full lexical scope. That is, a variable shall be scoped according to it's lexical position in the code.

It shall not be not-scoped because of some arbitrary constraint of the language in question.

Make a related claim about 1 year ago (link)
Sign in in to leave a comment.