Object reference comparison in JavaScript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Object reference comparison in JavaScript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m recently trying to get deep into how ReactJS, and Redux works in terms of when do their hooks update.

Consider the playaround I’ve made:

let state = { a: 1 };

//action happens, but no change
//comparison

const prevState = state;

state = state;

const nextState = state;

const equal = prevState === nextState ? "Yes" : "No";

console.log("Action - no change. Are they equal?", equal);

The above example is simple, both pointing to the same object.

See next example:

let state = { a: 1 };

//action happens, change in state
//comparison

const prevState = state;

state = { ...state, b: 2 };

const nextState = state;

const equal = prevState === nextState ? "Yes" : "No";

console.log("Action - no change. Are they equal?", equal);

Although it makes sense now how comparison works for the hooks, but not completely why.

We’re changing state, the object itself, but it will be the same reference no matter what value it gets right? So what am I understanding wrong? Is object reference for the value, or declaration, or both?

Answer

We’re changing state, the object itself,

No, that code isn’t. Specifically

state = { ...state, b: 2 };

allocates a new, referentially distinct object that is initialized with properties from the previous referent of state.

That line isn’t changing the object itself; it’s assigning a distinct object reference to the cell state.

To change the content of state, you could do

state.b = 2;

which will work as long as the property referred to by state.b doesn’t exist as an own property, is configurable, or there’s a setter on the prototype chain.

We are here to answer your question about Object reference comparison in JavaScript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji