Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why object destructuring isn't work at style?

The HTMLelement is an object. The style is an object too. So why this code doesn't work? Without destructuring everything works fine, so it isn't a big problem, i just want to know the reason.

const changeColor = () => {
  const div = document.querySelector("div");
  let {color, background} = div.style;
  color = "red";
  background = "blue";
}
div{
  width: 300px;
  height: 150px;
  color: blue;
  background: red;
}
<div onClick = "changeColor()">
  <p>Example</p>
</div>
like image 431
Gergő Horváth Avatar asked Jun 08 '26 17:06

Gergő Horváth


2 Answers

destructuring just creates new local variables which means that

let {color, background} = div.style

is essentially equivalent to

let color = div.style.color
let background = div.style.background

and if you then follow those lines with

color = "red"
background = "blue"

You have not assigned a new object property to anything, you've only assigned new values for local variables.

like image 112
zzzzBov Avatar answered Jun 10 '26 06:06

zzzzBov


This:

const changeColor = () => {
  const div = document.querySelector("div");
  let {color, background} = div.style;       // ***
  color = "red";
  background = "blue";
};

is exactly the same as this other than that div.style is evaluated once, not twice:

const changeColor = () => {
  const div = document.querySelector("div");
  let color = div.style.color;               // ***
  let background = div.style.background;     // ***
  color = "red";
  background = "blue";
};

Changing the local variable doesn't have any effect on the object property in either case. The local variable got the value of the object property, it has no enduring link back to it.

Putting it another way: Destructuring just creates locals, it doesn't create an object that's a kind of "view" onto the original object providing accessors to the original object's properties. (That would be kind of interesting, but it's not what destructuring does.)

You could do this, though:

const changeColor = () => {
  const {style} = document.querySelector("div");
  style.color = "red";
  style.background = "blue";
};

That works because we're grabbing a reference to the div's style object and modifying its properties directly.

Or, leaving destructuring behind entirely:

const changeColor = () => {
  Object.assign(document.querySelector("div").style, {
      color: "red",
      background: "blue"
  });
};

and if the function accepts those as parameters, then:

const changeColor = (color, background) => {
  Object.assign(document.querySelector("div").style, {color, background});
};

which you'd call via changeColor("red", "blue");.

like image 28
T.J. Crowder Avatar answered Jun 10 '26 08:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!