Skip to content

Instantly share code, notes, and snippets.

@marcandrewb
Created December 14, 2017 16:22
Show Gist options
  • Save marcandrewb/a77f424f9a54bc690a0bbf2283120e18 to your computer and use it in GitHub Desktop.
Save marcandrewb/a77f424f9a54bc690a0bbf2283120e18 to your computer and use it in GitHub Desktop.
for of | for in Cheatsheet
  • for...in iterates over the enumerable properties of an object
  • for...of iterates over the property values of objects
let myString = "test";

// logs 0, 1, 2, 3
for (let i in myString) {
  console.log(i);
}

// logs t, e, s, t
for (let i of myString) {
  console.log(i);
}
  • for...in should not be used if the index order of the items is important because there is no guarantee they will be given in the intended order
  • If you only want to iterate over an object's own properties, use getOwnPropertyNames() or something similar, instead of for...in.
  • You can use const as the variable for either loop, as long as you're not trying to change the value of the variable (thus obeying the rules of const)
  • You can use statements like break or return to terminate either of these loops before they complete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment