Saturday, July 9, 2016

Difference between for..in and for..of loop in javascript


There is an difference b/w the two javascript loop for..in and for..of
Ø  for..in:
The for..in loop works with array and objects. It iterates with the property name.
1.1    When working with array it returns the indexes of the array element and user defined properties.

eg.
var arr=[12,13,14,15];
arr.foo='abc';
for (index in arr)
console.log(index);  // use arr[index] to access the element
Result:
0
1
2
3
foo
1.2    When working with object it returns the ‘key name’ of the object.

Eg.
var obj={key1:12,key2:13,key3:14,key4:15};
for (key in obj)
console.log(key); // use obj[key] to access the element
Result:
key1
key2
key3
key4

Ø  for..of: It works only with iterable objects. Iterable objects are those object that use Iterable protocol.
Inbuilt iterable objects are Array, String, Map, Set, TypedArray. Iterable object have the @@iterator method (i.e Symbol.iterator key). It iterates with the property value.

Eg.
var arr=[12,13,14,15];
arr.foo='abc';
for (index of arr)
console.log(index);  
Result:
12
13
14

15