# Function definition throwing UndefVarError

**URL:** <https://discourse.julialang.org/t/function-definition-throwing-undefvarerror/56845>\
**Category:** New to Julia\
**Tags:** question, error-message\
**Created:** [March 10, 2021, 1:46am UTC](https://discourse.julialang.org/t/function-definition-throwing-undefvarerror/56845 "2021-03-10T01:46:51Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [March 10, 2021, 3:11am UTC](https://discourse.julialang.org/t/function-definition-throwing-undefvarerror/56845/2 "2021-03-10T03:11:50Z")

</div>

Wow, that’s really weird. Even worse is that even if you didn’t get an `UndefVarError`, you’d still get the wrong answer due to the issue discussed here: [Conditional function definition](https://discourse.julialang.org/t/conditional-function-definition/27348)

The fix for both problems is to use an anonymous function:

```julia
using Statistics: std, mean, median, var
function foo(a,b,c)
    """
    Do some stuff 
    """

    if a > 0
        if a == 1
            bar = x -> std(x, corrected=false)
        elseif a == 2
            bar = x -> var(x, corrected=false)
        elseif a == 3
            bar = x -> mean(abs.(x .- mean(x)))
        elseif a == 4
            bar = x -> median(abs.(x .- median(x)))    
        end
    else
        """
        Do some other stuff instead
        """
    end

    return c*bar(b)
end

```

(this will still error unless `a` is 1, 2, 3, or 4, in which case `bar` really is undefined.)

---

_[View the full topic](https://discourse.julialang.org/t/function-definition-throwing-undefvarerror/56845)._
