assign multiple const to the same value in Javascript

Tags:



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');

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"));


Source: stackoverflow