# While loop and UndefVarError

**URL:** https://discourse.julialang.org/t/while-loop-and-undefvarerror/52940
**Category:** New to Julia
**Tags:** question
**Created:** [January 6, 2021, 2:34pm UTC](https://discourse.julialang.org/t/while-loop-and-undefvarerror/52940 "2021-01-06T14:34:37Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Aman\_Atman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/aman_atman/32/20248_2.png) [@Aman\_Atman](https://discourse.julialang.org/u/Aman_Atman)
#### Post date: [January 6, 2021, 2:34pm UTC](https://discourse.julialang.org/t/while-loop-and-undefvarerror/52940/1 "2021-01-06T14:34:37Z")

</div>

The variable gets undefined in a while loop.

```julia
julia> index = length(fruits)
4

julia> while index > 0
           println(fruits[index])
           index -= 1
       end
ERROR: UndefVarError: index not defined
Stacktrace:
 [1] top-level scope at ./REPL[7]:2

julia> index
4

```

---

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [January 6, 2021, 2:43pm UTC](https://discourse.julialang.org/t/while-loop-and-undefvarerror/52940/2 "2021-01-06T14:43:49Z")

</div>

> [@Aman\_Atman](#):
>
> ```julia
> while index > 0
> println(fruits[index])
> index -= 1
> end
> 
> ```

What version of Julia are you using? The short answer is you need to add `global index` inside the loop, because the scope of the loop is local and does not “see” the global index variable unless you explicitly tell him to do it.

The even shorter answer is that if you download Julia 1.5 or greater you won’t get that error anymore, and your loop will work as you expect. I would recomend that, to avoid confusion.

---

<div class="post-metadata">

### Author: ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)
#### Post date: [January 6, 2021, 2:57pm UTC](https://discourse.julialang.org/t/while-loop-and-undefvarerror/52940/3 "2021-01-06T14:57:01Z")

</div>

Also, if your loop is inside a function (and `index` is defined inside the function) this will not happen in any version of Julia.
