Thursday, 17 September 2020

For/in vs For/of statement in Javascript

 For/in Statement :

==================

1.Iterates over elements of object (properties and methods)

2.Returns Key (property/method) name.

3.Object[key] returns value.


ex : for(const key in product){

      console.log("'"+ key + "'=" + product[key]);

     }

Note : The 'in' keyword grabs all property and method names from an object.


Any object in javascript can use the dot notation or an index to retrieve a value.

 ex: product.productId

     product["productId"]


For/of Statement :

==================

1.Iterates over values in array,string, etc.

2.Returns object for each iteration.


ex: Looping over a array


for(const item of _Products){

     console.log(JSON.stringify(item));

  }


Note : The 'of' keyword keeps track of which item in the array is currently being accessed.


ex: Looping over a string


let productName='HL Road Frame - Black, 58";

let letters ="";

for(const char of productName){

  letters +=char;

}  

console.log(letters);  // HL Road Frame - Black, 58


Break and Continue :

====================

1.Break: Leave a loop early

2.Continue: Next iteration of a loop.


ex: break statement


  for(const item of _Products){

    if(item.standardCost <20){

  break;

}

console.log(JSON.stringify(item));

  }

  

ex : continue statement

  for(const item of _Products){

      if(item.standardCost>1000){

    continue;

  }

console.log(JSON.stringify(item)); 

  }


The continue statement goes back to the loop, and increments the internal variable keeping track of which item is the current one.


Summary :


1.for/in for object properties/methods.

 (or)

  for/in iterates over all enumerable property keys of an object.

2.for/of for iterable objects.

(or)

for/of iterates over the values of an iterable object.

Examples of iterable objects are arrays,strings,and NodeLists.


No comments:

Post a Comment