2

Can someone explain why the following code would log false to the console?

const object = { title: 'object', data: 2 };
localStorage.setItem('object', JSON.stringify(object));
console.log(object === JSON.parse(localStorage.getItem('object')));
Taouen
  • 65
  • 7
  • 2
    Two objects in memory are not equal if they reside in different spaces in memory. – Taplar Jul 17 '20 at 23:09
  • this may be helpful: https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – redouglas Jul 17 '20 at 23:10

1 Answers1

2

It's because by using JSON.stringify and then JSON.parse you are converting your Object type to a string which is a new Object type which means it's a new object with it's own independent reference in memory, and by comparing the objects you are comparing their reference in memory that's why they are not equal.

Sven.hig
  • 4,449
  • 2
  • 8
  • 18