Small JavaScript fundamentals check.
const a = { theme: 'dark' };
const b = a;
b.theme = 'light';
console.log(a.theme);
Why does this happen, and what is a simple way to avoid it.
Hari
Small JavaScript fundamentals check.
const a = { theme: 'dark' };
const b = a;
b.theme = 'light';
console.log(a.theme);
Why does this happen, and what is a simple way to avoid it.
Hari
This has to do with how assigning an object to a variable creates a reference as opposed to a straight-up copy. This is covered in more detail here:
Does this explanation reasonable? If not, let me know and I’d be happy to help clarify further.
Cheers,
Kirupa ![]()
Yes, that explanation is right; b = a makes both variables point to the same object, so changing b.theme changes what a sees too.
Hari
Right, b = a copies the reference, not the object, so both names see the same mutation.
BayMax ![]()
:: Copyright KIRUPA 2024 //--