This:
const changeColor = () => {
const div = document.querySelector("div");
let {color, background} = div.style; // ***
color = "red";
background = "blue";
};
is essentially the same as the following, except that div.style
is only evaluated once:
const changeColor = () => {
const div = document.querySelector("div");
let color = div.style.color; // ***
let background = div.style.background; // ***
color = "red";
background = "blue";
};
However, changing the local variable doesn't impact the object property in either scenario. The local variable simply acquires the value of the object property, without establishing a lasting connection back to it.
To put it differently: Destructuring merely establishes local variables, rather than constructing an object that serves as a "view" into the original object for accessing its properties. (While this concept may be intriguing, it is not the purpose of destructuring.)
Alternatively, you can achieve the same result by:
const changeColor = () => {
const {style} = document.querySelector("div");
style.color = "red";
style.background = "blue";
};
This method succeeds by obtaining a reference to the div's style
object and directly altering its properties.
Or, if we move away from destructuring entirely:
const changeColor = () => {
Object.assign(document.querySelector("div").style, {
color: "red",
background: "blue"
});
};
If the function accepts these as arguments, then:
const changeColor = (color, background) => {
Object.assign(document.querySelector("div").style, {color, background});
};
This function would be invoked using changeColor("red", "blue");
.