Temporary variable in for loops

as I recall and with Wikipedia’s help:

In computer programming, a temporary variable is a variable with short lifetime, usually to hold data that will soon be discarded, or before it can be placed at a more permanent memory location. Because it is short-lived, it is usually declared as a local variable , i.e., a variable with local scope.

in lessons the variable used in for <var> in ... is called a temporary variable while it can be used after for loop is finished with its last value.
Is this a mistake in lessons or am I getting it wrong?

that depends on what keyword is used, if no keyword is like so:

for (item in obj)

then yes. But essentially then you have a leak, a variable exists outside the scope.

if you do:

for (let item in obj)

then not. let and const are block-scoped. If you don’t need to change the variable during the loop, using const would be even better.

1 Like

i have’t seen these in lessons yet, am i going to learn them here or i have to search my self?

these? you mean let and const? They are in the JS es6 course:


in the beginning, 1. introduction > variables. Which Javascript course are you doing then?

learning about let and const is highly recommended. You can indeed search for this yourself if you feel like it :slight_smile:

i’m talking about python course, Flow, Data, and Iteration

Oops, sorry. I messed up.

Yea, in python its not possible to prevent the loop from leaking its temporary variable.The only thing you could do is make a function to run the loop.

so technically it’s not a temporary variable. right?

Not really, ideally it should be. And in many language it is. Every language has its quirks.

1 Like