2

function bla() { a=5; }

Does a automatically become a global variable?

And when exactly is it set? when the functions are being read for the first time and put into memory or only at the execution of the function?

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
ilyo
  • 35,851
  • 46
  • 106
  • 159

3 Answers3

4

If you assign to a variable inside a function without declaring it with var then it becomes a global.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
4

The variable becomes a global when the function is first executed.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1

As soon as the function is executed, it puts the variable in global. Just like a function containing var a = 5 - it isn't executed until you actually call the function.

You can confirm this using a function: you don't get the alert until you call the function.

function x() {
 alert(123);
 return 1;
}

function bla() {
 a = x();
}
pimvdb
  • 151,816
  • 78
  • 307
  • 352