trapmm

JS for each / of loops

Oct 27th, 2020 (edited)
860
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ARRAY: For…Of Loop
  2. // Initialize array of shark species
  3. let sharks = [ "great white", "tiger", "hammerhead" ];
  4.  
  5. // Print out each type of shark
  6. for (let shark of sharks) {
  7.     console.log(shark);
  8. }
  9. // Loop through both index and element
  10. for (let [index, shark] of sharks.entries()) {
  11.     console.log(index, shark);
  12. }
  13. // OBJECT: For.. In Loop
  14. const shark = {
  15.     species: "great white",
  16.     color: "white",
  17.     numberOfTeeth: Infinity
  18. }
  19. for (attribute in shark) {
  20.     //property names
  21.     console.log(attribute);
  22.     // property value
  23.     console.log(shark[attribute]);
  24. }
  25.  
RAW Paste Data