title: Scope of for loops in julia
body: <p>From the <a href="https://lectures.quantecon.org/jl/julia_by_example.html" rel="nofollow noreferrer">Quantitative Economics course</a>, I came across the following example:</p>
  
  <pre><code>ϵ = randn(1:100)
  ϵ_sum = 0.0
  m = 5
  for ϵ_val in ϵ[1:m]
      ϵ_sum = ϵ_sum + ϵ_val
  end
  ϵ_mean = ϵ_sum / m
  </code></pre>
  
  <p>The code spits out an error <code>ERROR: UndefVarError: ϵ_sum not defined</code>, even though ϵ_sum was defined in first line of the code. After some painful browsing of the internet, the hypothesis was that the <a href="https://github.com/JuliaLang/julia/issues/28789" rel="nofollow noreferrer">for loop has weird local completely isolated scope</a>. This seems to be the case, as similar code that I have been trying to port from matlab has weird issues in julia, particularly code growing arrays and variables in for loops. </p>
  
  <p>But the hypothesis of the local scope in for loops is discarded, because the following code runs without an issue:</p>
  
  <pre><code>e = 1
  for num in 1:100
      println(e)
  end
  </code></pre>
  
  <p>What is the difference of the scope between the two pieces of code?</p>