0

I'm not quite sure why it is happening and it would be great if someone could explain this to me.

So i got the following code:

var text = 'yes';
(function f() {
    alert(text);
})();

And it alerts 'yes' as expected. But if I expand it like this:

var text = 'yes';
(function f() {
    alert(text);
    var text = 'no';
})();

I would pretty much expect this to alert 'yes' too and then overwrite the text variable in the local scope. But instead it alerts undefined.

This is tested in current Chrome and Firefox so this seems to be a wanted behavior?!

2 Answers 2

6

Variable (and function) declarations are hoisted to the top of the scope. So your code is equivalent to:

var text = 'yes';
(function f() {
    var text;    // shadows the outer variable; initialised with `undefined` 
    alert(text); // still undefined
    text = 'no'; // now it has the value 'no'
})();
Sign up to request clarification or add additional context in comments.

4 Comments

That was pretty much what I thought too whn thinking about the issue from a compiler viewpoint, but it was somewhat unexpected at first. Is this defined in the ECMAScript/Javascript definition?
Yes, you have to dig through it though. es5.github.com/#x10.4.3, es5.github.com/#x10.2.1.1 and es5.github.com/#x10.5 (especially this one) seem to be relevant.
Ok thanks. For everyone reading this later: it's called lexical scope :)
@bardiir: that behavior has no direct relationship with the lexical scope nature of ES. That just means that free (out of scope) variables are searched in parent-execution context objects (variable objects es3 or lexical environments in es5) in lexical order. The issue here really is that function and variable declarations are just interpretated at parsing-time (before evaluating time) and get always treated as if they were declared at the very first line.
1

You're declaring it as a new variable in that scope, so it won't override. Try:

var text = 'yes';
(function f() {
    alert(text);
    text = 'no';
})();

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.