Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript why FOR IN is a bad practice? [duplicate]

Tags:

javascript

Possible Duplicate:
JavaScript “For …in” with Arrays

People always tell me that using FOR IN is a bad practice, please could you tell me why? And why is better to use for with i?

I always liked to use FOR IN because I use PHP too where I use foreach a lot and it's very similar to FOR IN in javascript :)

like image 571
Adam Halasz Avatar asked Feb 04 '23 00:02

Adam Halasz


1 Answers

Bad practice is not to understand the difference between enumerating over an array object and iterating over it. Otherwise for...in loop is excellent tool. There is big internal difference, but i will try to explain in the practical manner:

Syntax is: for (string in object), where object is an instance of Object (and, naturally, any of its descendants) and string var receives property name of object on each loop iteration. But Array is an Object descendant too! So, it is perfectly legal to use:

var array = [0,1,2];
for (var property in array)
  alert(typeof property + '\t' + property + '\n' + typeof array[property] + '\t' + array[property]);

but simply makes no sense at all. Moreover, note the bracket notation above []. This is a form of membership operator and must not be confused with array element access. First requires operand of type string and second - number. Lets break example above and create array with var array = new Array(3) instead. Loop works no longer, yet array.length == 3 correctly.

Conclusion: use for...in for any objects except arrays. Use for (var number = 0; number < array.length; number++) with arrays.

By the way, JavaScript objects are similar with PHP's associative arrays (hashtables, if you insist on the proper term). Syntax is var object = {string:value,anotherName:moreStuff}. Here for...in comes handy!

Further reading

like image 188
Free Consulting Avatar answered Feb 05 '23 14:02

Free Consulting