Wednesday, 2 January 2013

Javascript Variable Scope Caveats

I ran into a strange Javascript variable scope issue. I am not satisfied with the documentation I found so far, hence this post:
  • A variable aaa declared outside of a function is global.
  • If a function f1 declares a aaa variable in its code using var, all modifications made to this variable is local and the global aaa variable is not impacted.
  • If one uses the f1 local aaa variable in f1 code before it is declared, Javascript will consider it undefined.
  • If a function f2 does not declare a local aaa variable in its code, it can access the global aaa variable by using its name. All modifications are registered in the global variable.
  • Passing a global variable as a parameter to a function, and modifying this parameter inside that function does not modify the global variable.

No comments:

Post a Comment