Scoping in nested functions - Why am I not getting an error?

This is documented in the manual:
https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Local-Scope-1

Note that nested functions can modify their parent scope’s local variables:

julia> x, y = 1, 2;

julia> function baz()
          x = 2 # introduces a new local
          function bar()
              x = 10       # modifies the parent's x
              return x + y # y is global
          end
          return bar() + x # 12 + 10 (x is modified in call of bar())
      end;

julia> baz()
22

julia> x, y # verify that global x and y are unchanged
(1, 2)

The reason to allow modifying local variables of parent scopes in nested functions is to allow constructing closures which have private state

In your example, the function is defined before the variable that it modifies, but the compiler doesn’t care of that — just as in the case of variables defined in the global scope.

3 Likes