# UndefVarError on a defined variable

**URL:** <https://discourse.julialang.org/t/undefvarerror-on-a-defined-variable/95686>\
**Category:** New to Julia\
**Created:** [March 7, 2023, 5:25pm UTC](https://discourse.julialang.org/t/undefvarerror-on-a-defined-variable/95686 "2023-03-07T17:25:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ossan05](https://avatars.discourse-cdn.com/v4/letter/o/e0b2c6/32.png) [@ossan05](https://discourse.julialang.org/u/ossan05)\
**Post date:** [March 7, 2023, 5:25pm UTC](https://discourse.julialang.org/t/undefvarerror-on-a-defined-variable/95686/1 "2023-03-07T17:25:10Z")

</div>

My script in which i have defined a variable (b) as an empty string gives an error saying my variable isn’t defined.

```julia
c = "abc"
b = ""
res = []

for i in 1:4
    for i in 1:4
        b * c[rand(1:3)] # this line gives the error
    end
    push!(res, b)
    b = ""
end

```

I tried using the global keyword before b in the last line but that made it so res became a list of empty strings.

---

<div class="post-metadata">

**Author:** ![SteffenPL](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/steffenpl/32/206270_2.png) [@SteffenPL](https://discourse.julialang.org/u/SteffenPL)\
**Post date:** [March 7, 2023, 5:37pm UTC](https://discourse.julialang.org/t/undefvarerror-on-a-defined-variable/95686/2 "2023-03-07T17:37:56Z")

</div>

If you do not execute your script within the REPL, then there are strict rules about where variables are accessible.

The documentation about this is here [Scope of Variables · The Julia Language](https://docs.julialang.org/en/v1/manual/variables-and-scoping/)

But there are also many posts in this forum where the behavior is explained. See for example [Undefined variable in loop - New to Julia - Julia Programming Language (julialang.org)](https://discourse.julialang.org/t/undefined-variable-in-loop/72936) for a more recent one.

* * *

In your case:

- It should work if you add the global keyword, e.g. `global b *= c[rand(1:3)]`. Note that your code does not update `b`, but just computes something without updating `b`.
- If you use VS Code or Atom/Juno, then you could run you code by selecting and “Shift + Enter”, in which case the rules for REPL apply which are a bit less strict.

---

<div class="post-metadata">

**Author:** ![ossan05](https://avatars.discourse-cdn.com/v4/letter/o/e0b2c6/32.png) [@ossan05](https://discourse.julialang.org/u/ossan05)\
**Post date:** [March 7, 2023, 6:10pm UTC](https://discourse.julialang.org/t/undefvarerror-on-a-defined-variable/95686/3 "2023-03-07T18:10:37Z")

</div>

I changed it a little bit with your help and this worked:

```julia
c = "abc"
res = []

for i in 1:4
    b = ""
    for j in 1:4
        b *= c[rand(1:3)]
    end
    push!(res, b)
end

println(res)

```
