# Why the free variables in function body don't get bound at function definition time?

**URL:** <https://discourse.julialang.org/t/why-the-free-variables-in-function-body-dont-get-bound-at-function-definition-time/128860>\
**Category:** New to Julia\
**Tags:** offtopic, design\
**Created:** [May 9, 2025, 3:29am UTC](https://discourse.julialang.org/t/why-the-free-variables-in-function-body-dont-get-bound-at-function-definition-time/128860 "2025-05-09T03:29:11Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![palday](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/palday/32/12640_2.png) [@palday](https://discourse.julialang.org/u/palday)\
**Post date:** [May 9, 2025, 5:08am UTC](https://discourse.julialang.org/t/why-the-free-variables-in-function-body-dont-get-bound-at-function-definition-time/128860/4 "2025-05-09T05:08:43Z")

</div>

This follows directly from Julia’s use of lexical scope.: the `a` in the functions you defined refers to the _global variable_ `a`, not the value of the variable at definition.

I think it can help to realize that

```julia
fun() = a

```

isn’t assigning the value of `a` to a function, but rather is syntactic sugar for

```julia
function fun()
   return a
end

```

If you really want the behavior you described, then you need to close over / capture the value at definition time, i.e. you need a _closure_. You can do this with a `let` block:

```julia
julia> a = 1
1

julia> fun = let a2 = a
       function()
       return a2
       end
       end
#3 (generic function with 1 method)

julia> fun()
1

julia> a = 2
2

julia> fun()
1

julia> a2
ERROR: UndefVarError: `a2` not defined in `Main`
Suggestion: check for spelling errors or missing imports.

```

---

_[View the full topic](https://discourse.julialang.org/t/why-the-free-variables-in-function-body-dont-get-bound-at-function-definition-time/128860)._
