DEV Community

Discussion on: How to iterate over an object in Javascript?

peerreynders profile image
peerreynders • Edited on

I encountered a problem where I had to create a hashmap using an empty Object.

An object is only really viable if you are using strings (or symbols) as keys. Anything else is coerced to a string with .toString() including numbers.

So consider using a Map instead (it's an iterable so it can be directly iterated).

const map = new Map([
  ['name', 'Rakshit'],
  ['age', 23],
  ['gender', 'Male'],

for (const [key, value] of map) {
  console.log(`${key}: ${value}`);
Enter fullscreen mode Exit fullscreen mode

Map - JavaScript | MDN

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

rakshit profile image
Rakshit Author

Makes sense, thank you so much :)