Referencing local variable before assignment results in unexpected behavior

I think I see how these two sentences are throwing OP off.

Explicit declaration works in Julia too: in any local scope, writing local x declares a new local variable in that scope, regardless of whether there is already a variable named x in an outer scope or not.

This part is pretty straightforward. local x declares a new variable in its scope, different from other variables named x in outer scopes.

Declaring each new local like this is somewhat verbose and tedious, however, so Julia, like many other languages, considers assignment to a new variable in a local scope to implicitly declare that variable as a new local.

This following sentence seems to suggest that local x is an optionally explicit keyword for something that Julia already does by default…if the reader doesn’t pick up on a subtle detail. Elsewhere in these two sentences, “new variable”/“variable as a new local” meant the variable was new to the declaration or assignment’s scope, but “new variable in a local scope” meant the variable was also new to all local scopes containing the assignment’s scope.

I think it’s pretty understandable for someone unfamiliar with all this terminology to read “this variable is local to its scope” and think “local variable” implies a context specific to the variable’s home scope. Maybe it’s simpler to tell people:

  1. The global scope contains local scopes that can contain other local scopes
  2. we call a variable in the global scope a global variable
  3. we call a variable in any local scope a local variable
  4. inner scope can access a variable that it does not declare or assign from an outer scope
  5. inner local scope assigns to existing variables from outer local scopes by default
  6. local scope does not assign to global variables except in interactive contexts e.g. REPL because unlike local scopes, the global scope is not contained to one file.
10 Likes