Skip to content
Advertisement

assign multiple const to the same value in Javascript

Is something like this possible? I have tried using let with no success after some research.

const [container, item, columnLeft, columnRight] = document.createElement('div');

or

let [container, item, columnLeft, columnRight] = document.createElement('div');

Advertisement

Answer

The thing on the right has to match the destructuring thing on the left, in your case the thing on the left is looking for an array with at least four elements, so:

const [container, item, columnLeft, columnRight] = [
  document.createElement("div"),
  document.createElement("div"),
  document.createElement("div"),
  document.createElement("div")
];

or, make a temporary array and use its map method to produce the array of divs

const [container, item, columnLeft, columnRight] = [1,2,3,4].map(() => document.createElement("div"));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement