Are they the same?

While debugging I needed to know if two references in two separate parts of my codebase were pointing to the same object in memory. According to my searching, there isn’t a way to print out memory addresses of data in Javascript (without using special V8 debugging expressions). But there’s a way to find the answer to this question, regardless!

Maps allow objects as keys

In short, we can create a global Map from objects to random strings, and get an approximation of object IDs:

// DebuggingIDs.ts

let objectIds = new Map();

export function getObjectIdFor(thing: any): number {
  if (!objectIds.has(thing)) {
    objectIds.set(thing, Math.random().toString(16).slice(2, 10));
  }
  return objectIds.get(thing);
}

This function will take any object, and assign a random hex string to it. Any time that same object is passed to this function, the same string will be returned. This is possible becuase the ES6 Map data structure allows objects to be used as keys. When an object is used as a key, it’s memory reference is used to determine equality, rather than its structure.

let thing1 = {hello: 1}
console.log(getObjectIdFor(thing1)) // Prints "2149Ef2b"
console.log(getObjectIdFor({hello: 1})) // Prints "3a720fef"
console.log(getObjectIdFor(thing1)) // Prints "2149Ef2b"

This allowed me to drop two log statements for two different variables in different files, and verify that both references pointed to the same object in memory.

Credit

Thanks to ArthurJ on dev.to for originally publishing this idea! https://dev.to/arthurbiensur/kind-of-getting-the-memory-address-of-a-javascript-object-2mnd


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *