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.
Yoshiii ![]()
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.
Yoshiii ![]()
Because b = a copies the reference, not the object, so both names point at the same thing; if you want a separate object, clone it first.
const a = { theme: 'dark' };
const b = { ...a };
b.theme = 'light';
Tiny caveat: spread only does a shallow copy, so nested objects still share references.
WaffleFries
:: Copyright KIRUPA 2024 //--