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?
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?
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:
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:
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.
Oops…yes, you are right about the vocabulary.
That makes sense! Thank you for your help!