# Scope of variable in if in loop

**URL:** <https://discourse.julialang.org/t/scope-of-variable-in-if-in-loop/62621>\
**Category:** General Usage\
**Tags:** question\
**Created:** [June 9, 2021, 12:31pm UTC](https://discourse.julialang.org/t/scope-of-variable-in-if-in-loop/62621 "2021-06-09T12:31:41Z")\
**Posts on this page:** 1\
**Showing post:** 3

<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:** [June 9, 2021, 12:45pm UTC](https://discourse.julialang.org/t/scope-of-variable-in-if-in-loop/62621/3 "2021-06-09T12:45:05Z")

</div>

The behavior you see is the expected behavior. The `if` statement does not create a new scope, but the `for` creates a new scope _for each iteration_. So `b` will never be defined inside any loop besides the first. You need to declare it one scope above for your code to work (i.e., outside the `for`).

I wrote a better answer to a very similar question in the past: [I thought I understood "pass-by-sharing" in Julia until I found this - #19 by Henrique\_Becker](https://discourse.julialang.org/t/i-thought-i-understood-pass-by-sharing-in-julia-until-i-found-this/46897/19)

---

_[View the full topic](https://discourse.julialang.org/t/scope-of-variable-in-if-in-loop/62621)._
