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.

Iain
  • 307
  • 4
  • 17
  • 2
    That's not local without `var msg...` inside the functions. – Jared Farrish Jun 23 '12 at 21:10
  • 1
    https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals#Variable_scope (the whole guide is worth a read if you are new to JavaScript) – Felix Kling Jun 23 '12 at 21:11
  • I used to be really confused by variable scope, and then I learned to [shut up and love the closure scope](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work). – Jared Farrish Jun 23 '12 at 21:13

1 Answers1

5

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

var msg = "1111";

Otherwise the value escapes into the global scope.

matt3141
  • 4,303
  • 1
  • 19
  • 24
  • Not to be picky, but the `"1111"` and `"2222"` are also a little odd. – Jared Farrish Jun 23 '12 at 21:14
  • 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! – Iain Jun 23 '12 at 21:19
  • Just think of it as without the `var` to declare the variable, it assumes the variable is present in the global scope. – matt3141 Jun 23 '12 at 21:22