Today I Learned - Rocky Kev

TIL Equality Comparisons for objects

POSTED ON:

TAGS:

[ 1, 2, 3 ] === [ 1, 2, 3 ];    // false
{ a: 42 } === { a: 42 }         // false
(x => x * 2) === (x => x * 2)   // false

JS does not define === as structural equality for object values.
Instead, === uses identity equality for object values.

The referential equality (using === or Object.is()) determines whether the operands are the same object instance.

Instead, you'll have to use a function to do the comparison.

Shallow Equal
Lighter, faster.

const hero1 = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};
const hero2 = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};
const hero3 = {
  name: 'Joker'
};

shallowEqual(hero1, hero2); // => true
shallowEqual(hero1, hero3); // => false

Fails with nestled objects.

const hero1 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
const hero2 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};

shallowEqual(hero1, hero2); // => false



**Deep Equal**
For accurate comparison.

function deepEqual(object1, object2) {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);

if (keys1.length !== keys2.length) {
return false;
}

for (const key of keys1) {
const val1 = object1[key];
const val2 = object2[key];
const areObjects = isObject(val1) && isObject(val2);
if (
areObjects && !deepEqual(val1, val2) ||
!areObjects && val1 !== val2
) {
return false;
}
}

return true;
}

function isObject(object) {
return object != null && typeof object === 'object';
}


const hero1 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
const hero2 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};

deepEqual(hero1, hero2); // => true

[reference](https://dmitripavlutin.com/how-to-compare-objects-in-javascript/)

Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.