Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save DoctorDerek/c4528ead671aabd8129f6c6ee8947a9d to your computer and use it in GitHub Desktop.

Select an option

Save DoctorDerek/c4528ead671aabd8129f6c6ee8947a9d to your computer and use it in GitHub Desktop.
Are JavaScript Object Keys Ordered and Iterable?
// Typical object declared with object literal notation
const myObject = { zap: "⚑" }
myObject.boom = "πŸ’£"
// ES5 version using for...in loop
for (const key in myObject) {
if (myObject.hasOwnProperty(key)) {
console.log(`myObject["${key}"] is ${myObject[key]}`)
}
}
// Output:
// myObject["zap"] is ⚑
// myObject["boom"] is πŸ’£
// ES6 version using Object.entries()
for (const [key, value] of Object.entries(myObject)) {
console.log(`myObject["${key}"] is ${value}`)
}
// Output:
// myObject["zap"] is ⚑
// myObject["boom"] is πŸ’£
// Compare to using an ES6 Map object:
const myOrderedMap = new Map()
myOrderedMap.set("zap", "⚑")
myOrderedMap.set("boom", "πŸ’£")
for (const [key, value] of myOrderedMap) {
console.log(`myOrderedMap.get("${key}") is ${value}`)
}
// Output:
// myOrderedMap.get("zap") is ⚑
// myOrderedMap.get("boom") is πŸ’£
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment