apokryfos
apokryfos

Reputation: 40653

See if variables refer to the same object in chrome devtool

Assume I have code :

var a = {};
var b = {};
var c = a;

Obviously a !== b and a === c however it is very hard to see at a glance which variables refer to the same object. Is there a way to get the Chrome devtool to show something akin to a reference hash or similar so we can, at a glance, determine which variables refer to the same object?

I am aware of the rules regarding equality of JavaScript objects, my question is whether Chrome devtools offers any help in debugging so we don't have to do things like write manual a === b in the console to determine what equals what but rather see equal variables through visual inspection of watches or when hovering over variables.

Upvotes: 2

Views: 651

Answers (1)

Keith
Keith

Reputation: 24181

I've not seen anything in Chrome that does something like that,.

But if you don't mind installing a simple utility method, you could implement your own referencing system.

You could also easily extend this to show referencing on Objects using Object.entries etc.

const refs = new WeakMap();
let count = 0;

function showRef(obj) {
  const g = refs.get(obj);
  if (!g) {
    count++;
    refs.set(obj, count);
    return count;
  };
  return g;
}

const a = {};
const b = {};
const c = a;

const z = {a,b,c: {}};

console.log(`a = ${showRef(a)}`);
console.log(`b = ${showRef(b)}`);
console.log(`c = ${showRef(c)}`);

console.log(`z.a = ${showRef(z.a)}`);
console.log(`z.b = ${showRef(z.b)}`);
console.log(`z.c = ${showRef(z.c)}`);

Upvotes: 1

Related Questions