# Variables in Loops

**URL:** https://forum.code.org/t/variables-in-loops/33807
**Category:** Unit and Lesson Discussion
**Tags:** csp-unit-5
**Created:** [November 30, 2020, 2:28pm UTC](https://forum.code.org/t/variables-in-loops/33807 "2020-11-30T14:28:41Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![elizabeth.handy](https://avatars.discourse-cdn.com/v4/letter/e/ba8739/32.png) [@elizabeth.handy](https://forum.code.org/u/elizabeth.handy)
#### Post date: [November 30, 2020, 2:28pm UTC](https://forum.code.org/t/variables-in-loops/33807/1 "2020-11-30T14:28:41Z")

</div>

We have begun Unit 5 Lesson 5 and one of my students had a great question this morning. Can you call a variable in a while/for loop out of the loop later?

I keep going back and forth…yes - no. Can anyone help?

---

<div class="post-metadata">

### Author: ![jdonwells](https://sea2.discourse-cdn.com/flex016/user_avatar/forum.code.org/jdonwells/32/7900_2.png) [@jdonwells](https://forum.code.org/u/jdonwells)
#### Post date: [November 30, 2020, 3:18pm UTC](https://forum.code.org/t/variables-in-loops/33807/2 "2020-11-30T15:18:00Z")

</div>

First, tighten up the vocabulary. Variables are referenced. Functions are called. I don’t mean to single you out on this because I have to watch it too.

The short answer is maybe.

It all depends on the variable’s scope. In Unit 4 lesson 10 we learn about scope. Javascript scope wasn’t designed well. It is different than look alike languages C and Java. That may cause confusion.

If you do this:

```javascript
for (var i = 0; i < 4; i++) {
  var x = i * 2;
  console.log(i);
}
console.log(i);
console.log(x);

```

`i` and `x` are both global variables and can be referenced anywhere. In this example 1, 2, 3, 4, and 6 will be printed in the log.

In this example:

```javascript
function countToThree () {
  for (var i = 0; i < 4; i++) {
    var x = i * 2;
    console.log(i);
  }
}
countToThree();
console.log(i);
console.log(x);

```

`i` and `x` are defined within the function `countToThree` but nowhere else. An error is thrown for the last 2 lines because `i` and `x` are not defined.

Within scope constraints, all the variables can be referenced.

---

<div class="post-metadata">

### Author: ![elizabeth.handy](https://avatars.discourse-cdn.com/v4/letter/e/ba8739/32.png) [@elizabeth.handy](https://forum.code.org/u/elizabeth.handy)
#### Post date: [November 30, 2020, 3:33pm UTC](https://forum.code.org/t/variables-in-loops/33807/3 "2020-11-30T15:33:42Z")

</div>

Oops…yes, you are right about the vocabulary.

That makes sense! Thank you for your help!
