JavaScript using var with for in loops

Which one is correct, line 1 or line 2?

for (k in object ) { }
for ( var k in object ) { }

Both samples will work but using var is better for memory management.

Take for example the following object and a  for in loop created under a function named list():

var myObject = { color: "blue", size: "M", material: "cotton"};

Listing it using var as a prefix for k in the loop:

list = function(obName){
for (var k in obName) {
 console.log(k);
}
}
list(myObject);

The above method logs color, size, material. So far so good.

Now, if we attempt to ask for the value of k after the function has closed and exited, we will get the following error:
ReferenceError: k is not defined

That is good since k was only a temporary variable.

However, when we do not use var k to ground k as a local variable, we get a different outcome:

list2 = function(obName){
for ( k2 in obName) {
 console.log(k2);
}
}
list2(myObject);

The above method logs color, size, material. So far so good.

Now, if we attempt to ask for the value of k2 after the function has closed and exited, we will get “material” as a value, Which was the last value assigned to k2. That will stay in memory for as long as the program runs, which leads to memory leaks and a sluggish execution on larger programs.

More about memory management on my eBook JavaScript Objects Functions and Arrays Explained

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s