I have an API that calls me with {}
for a param that I need to replace.
But having trouble as in ... can you guess what happens below?
const log = console.log
const a = {}
log('a is ', a)
// cannot compare with either == or ===
if (a == {}) {
log('a is {}')
} else {
log('a is NOT {}')
}
// a is truthy too
const b = (a || 'not a')
console.log('b is ', b)
So given its both truthy and fails to compare I'm wondering how to replace it?
I'd also be interested to know why, what object comparison is going on under the hood.
my understanding was that:
==
tested for equal by value (comparison)===
tested for equal by reference (pointer to same object in memory).But i guess I need to do an actual comparison for objects? I'm using to doing this with unit test frameworks where toBe()
or toEqual
and toDeepEqual
work.
And WAT!
If all you need to do is detect if something is an empty object, something like this would probably work:
const a = {};
const b = { hello: 'world' };
const c = 'test';
function isEmptyObject(arg) {
return typeof arg === 'object' && Object.keys(arg).length === 0;
}
console.log(`a is ${isEmptyObject(a)}`);
console.log(`b is ${isEmptyObject(b)}`);
console.log(`c is ${isEmptyObject(c)}`);