What is the difference if I use one of the following to iterate javascript arrays:
for (var i = 0 ; i <abc.length :i++)
or
for (var i in abc.lengh)
Thank you.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For iterating the elements of an array, you should use this form:
For iterating the properties of an object, you should use this:
Though you can sometimes get away with using the second syntax on an array, you are asking for trouble because it will include custom properties that have been added to the array that are not array elements themselves and that can really confuse the code and lead to subtle or not-so-subtle bugs.
The addition of the
lenvariable in the first syntax is a speed optimization because fetching the length one into a local variable can be significantly faster than accessing the length property on every iteration of the loop. It is not required to do it this way. It can be done as this also: