3

I had a problem with some JavaScript functions that had me scratching my head for about an hour until some well-placed alert()'s revealed something which surprised me. One function was changing another function's local variables, it seems. I wrote a simple test script:

function first() {
    msg = "1111";

    second();

    alert(msg);
    }


function second() {
    msg = "2222";
    }

When I call first() I'd expect to get an alert box saying "1111" but I get "2222" instead. How is it that second() is affecting a local variable belonging to first()? Am I missing something or is this a bug?

I'm using Firefox 12.0.

3

1 Answer 1

5

The variable is only local when the var statement is used:

var msg = "1111";

Otherwise the value escapes into the global scope.

Sign up to request clarification or add additional context in comments.

3 Comments

Not to be picky, but the "1111" and "2222" are also a little odd.
Haha, in several years on and off with JavaScript (I do it for hobby not for work) this had completely evaded me until now. I've put var in front of msg=... and it works as expected. Thanks!
Just think of it as without the var to declare the variable, it assumes the variable is present in the global scope.

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.