JavaScript For...In VS For

What is the difference between ( for... in ) and ( for... of ) statements?

for in loops over enumerable property names of an object.

for of (new in ES6) does use an object-specific iterator and loops over the values generated by that.

In your example, the array iterator does yield all the values in the array (ignoring non-index properties).

JavaScript for...in vs for

The choice should be based on the which idiom is best understood.

An array is iterated using:

for (var i = 0; i < a.length; i++)
//do stuff with a[i]

An object being used as an associative array is iterated using:

for (var key in o)
//do stuff with o[key]

Unless you have earth shattering reasons, stick to the established pattern of usage.

difference between for loop and for-in loop in javascript

for (... in ...) is typically used to iterate through the properties of objects (which are what javaScript uses for associative arrays), while the typical for loop is used for sequential arrays.

In your example, you are really creating an associative array with the keys 0, 1, and 4. If you wanted a true javaScript array, you'd use a.push(0), a.push(1), etc... in order to add the values, sequentially, onto the end of the array.

With a sequential array, the syntax for (var i = 0; i < arr.length; i++) makes i count from 0 to 1 less than the length of the array. This will allow i to be equal to each index in the array, one-by-one, allowing you to access each element in that array.

With associative arrays, however, the keys are non-sequential, so making a variable count 'from 0 to 1 less than the length of the array' won't produce the desired results. In your example it is close to working because your manually created keys just happen to be 0, 1, and 4, which are almost sequential.

If you want to have an array with non-sequential keys--'non-contiguous' as in 0, 1, 4, etc..--you should probably use objects, not arrays, e.g.

var obj = {};
obj[0] = 0;
obj[1] = 1;
obj[4] = 4;

And then using the for (... in ...) loop would be the correct syntax.

For-Of Loop vs. For Loop

A bit of backnowledge to explain your question:

In Javascript, Objects (among these are Arrays) store properties in key-value pairs. That means that each assigned value has a key (the property name) to access it.
For example in

person[name] = 'Tom'

person is the Object, name the key and 'Tom' the corresponding value.

Arrays use indices (i.e. numbers) as keys:

array[5] = 10

Now, keep that in mind in the following explanation.

Let's start with the traditional for loop:

for(let i = 0; i < array.length; i++) {...}

This way of iterating over an array is the oldest of the bunch (as long as you are not using while-loops)
You'll find a corresponding way of writing a for loop in pretty much any (imperative) programming language. You'll notice, it is very explicit in the way it works. E.g. you could change the break-condition i < array.length to something else (e.g. i < array.length-1 for skipping the last position), or the step i++ (e.g. to i+=2), or start at a different index (e.g. let i = 5). You can iterate backwards instead of forwards through the array, if you want. Pretty much anything you can do in another for loop, you can do in this kind as well, if you know how.

Inside the brackets {...} you can then use i as a key to access the arrays values

Now this is all very powerful and nice, but it gets cumbersome to write every time, especially if in most of the cases you just want to iterate over an array. But luckily we have for-in:

For-in will retrieve you all the keys you have set yourself. With an array, you can use that to achieve the same result as above using

for(let i in array) {...}

Note however, that for-in is not only gonna give you the number keys from an array. It is also gonna work on other keys you have set yourself on any object:

let object = {
key1 : 'value',
key2 : 'value'
}

for(let i in object) {
console.log(i)
}

will log out 'key1' and 'key2' (yes, the keys as well are strings here).

For a bit more precise description of what keys exactly it will give you, have a look at the link below.

When would you use for-in? Whenever you want to call some code for each element of an array / (almost) each property of an object once. E.g. when you want to increment all values in an array by 1.
When not to use for-in? Don't use it if you need more granular control over the order you traverse the array in, or you don't want to hit all elements of the array, but only every second/third.

For an excellent resource on for-in loops I recommend Mozilla Developer Network

So, what are for-of loops then?

For-of loops are syntactically (i.e. the way you write them) very similar to for-in loops:

for(let v of array) {...}

However, for one, they are only going to work on so-called iterable objects (arrays are iterable). Second, you only get the values. They are no longer going to give you any keys!

let array = ['a', 'b', 'c']
for(let v of array) {
console.log(v)
}

logs 'a', 'b' and 'c'. You won't know anymore, what keys these values had!

So, when to use these? Every time you just need the values and don't care about the keys. E.g. if you just want to print the values.
When not to use them? If you want to swap elements of an array, if you want to reverse order. You can't even increment the values by 1 and store them back into the array, because for that, you would need to know their corresponding key.

For more information on for-in loops as well as what iterable actually means, again, I recommend the MDN

Javascript for..in vs for loop performance

Look at what's happening differently in each iteration:

for( var i = 0; i < p1.length; i++ ) 
  1. Check if i < p1.length
  2. Increment i by one

Very simple and fast.

Now look at what's happening in each iteration for this:

for( var i in p1 )

Repeat

  1. Let P be the name of the next property of obj whose [[Enumerable]] attribute is true. If there is no such property, return (normal, V,
    empty).

It has to find next property in the object that is enumerable. With your array you know that this can be achieved by a simple integer increment, where as the algorithm to find next enumerable is most likely not that simple because it has to work on arbitrary object and its prototype chain keys.

JavaScript Loops: for...in vs for

Don't use for..in for Array iteration.

It's important to understand that Javascript Array's square bracket syntax ([]) for accessing indicies is actually inherited from the Object...

obj.prop === obj['prop']  // true

The for..in structure does not work like a more traditional for..each/in that would be found in other languages (php, python, etc...).

Javascript's for..in is designed to iterate over the properties of an object. Producing the key of each property. Using this key combined with the Object's bracket syntax, you can easily access the values you are after.

var obj = {
foo: "bar",
fizz: "buzz",
moo: "muck"
};

for ( var prop in obj ) {
console.log(prop); // foo / fizz / moo
console.log(obj[prop]); // bar / buzz / muck
}

And because the Array is simply an Object with sequential numeric property names (indexes) the for..in works in a similar way, producing the numeric indicies just as it produces the property names above.

An important characteristic of the for..in structure is that it continues to search for enumerable properties up the prototype chain. It will also iterate inherited enumerable properties. It is up to you to verify that the current property exists directly on the local object and not the prototype it is attached to with hasOwnProperty()...

for ( var prop in obj ) {
if ( obj.hasOwnProperty(prop) ) {
// prop is actually obj's property (not inherited)
}
}

(More on Prototypal Inheritance)

The problem with using the for..in structure on the Array type is that there is no garauntee as to what order the properties are produced... and generally speaking that is a farily important feature in processing an array.

Another problem is that it usually slower than a standard for implementation.

Bottom Line

Using a for...in to iterate arrays is like using the butt of a screw driver to drive a nail... why wouldn't you just use a hammer (for)?

Javascript efficiency: 'for' vs 'forEach'

for

for loops are much more efficient. It is a looping construct specifically designed to iterate while a condition is true, at the same time offering a stepping mechanism (generally to increase the iterator). Example:

for (var i=0, n=arr.length; i < n; ++i ) {
...
}

This isn't to suggest that for-loops will always be more efficient, just that JS engines and browsers have optimized them to be so. Over the years there have been compromises as to which looping construct is more efficient (for, while, reduce, reverse-while, etc) -- different browsers and JS engines have their own implementations that offer different methodologies to produce the same results. As browsers further optimize to meet performance demands, theoretically [].forEach could be implemented in such a way that it's faster or comparable to a for.

Benefits:

  • efficient
  • early loop termination (honors break and continue)
  • condition control (i<n can be anything and not bound to an array's size)
  • variable scoping (var i leaves i available after the loop ends)

forEach

.forEach are methods that primarily iterate over arrays (also over other enumerable, such as Map and Set objects). They are newer and provide code that is subjectively easier to read. Example:

[].forEach((val, index)=>{
...
});

Benefits:

  • does not involve variable setup (iterates over each element of the array)
  • functions/arrow-functions scope the variable to the block

    In the example above, val would be a parameter of the newly created function. Thus, any variables called val before the loop, would hold their values after it ends.
  • subjectively more maintainable as it may be easier to identify what the code is doing -- it's iterating over an enumerable; whereas a for-loop could be used for any number of looping schemes

Performance

Performance is a tricky topic, which generally requires some experience when it comes to forethought or approach. In order to determine ahead of time (while developing) how much optimization may be required, a programmer must have a good idea of past experience with the problem case, as well as a good understanding of potential solutions.

Using jQuery in some cases may be too slow at times (an experienced developer may know that), whereas other times may be a non-issue, in which case the library's cross-browser compliance and ease of performing other functions (e.g., AJAX, event-handling) would be worth the development (and maintenance) time saved.

Another example is, if performance and optimization was everything, there would be no other code than machine or assembly. Obviously that isn't the case as there are many different high level and low level languages, each with their own tradeoffs. These tradeoffs include, but are not limited to specialization, development ease and speed, maintenance ease and speed, optimized code, error free code, etc.

Approach

If you don't have a good understanding if something will require optimized code, it's generally a good rule of thumb to write maintainable code first. From there, you can test and pinpoint what needs more attention when it's required.

That said, certain obvious optimizations should be part of general practice and not required any thought. For instance, consider the following loop:

for (var i=0; i < arr.length; ++i ){}

For each iteration of the loop, JavaScript is retrieving the arr.length, a key-lookup costing operations on each cycle. There is no reason why this shouldn't be:

for (var i=0, n=arr.length; i < n; ++i){}

This does the same thing, but only retrieves arr.length once, caching the variable and optimizing your code.

What is the different between for loop and for in loop in javascript

It depends on what you need. I usually use for-in loop because it is a shorter form, but sometimes you may want to have control over the iteration variable. For instance, if you want to iterate over even indices, you'd need to use the normal for loop:

for (var i = 0; i < myarray.length; i+=2) {...}

The same applies, for example, if you want to iterate backwards:

for (var i = myarray.length-1; i >= 0; i--) {...}

Certainly, for objects, the for-in loop allows you to get the property name in the iteration variable. For example:

var myobject = {year: 1992, city: "Barcelona"}
for (var propname in myobject) alert(propname + " = " + myobject[propname]);

In your example, I'd use for-in because you are doing a simple iteration. Moreover I think in a non-optimized Javascript compiler/interpreter, the for-in loop would be even faster because variable increment is done internally (i.e. it is not a Javascript statement such as "i++").



Related Topics



Leave a reply



Submit