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')));
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')));
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.