3

Can somebody explain, what this line of code represents in Javascript:

const [m, o] = [player.matrix, player.pos]

Im specifically confused by the square brackets around variable names?

searchfind
  • 47
  • 5

1 Answers1

4

This is what we call a destructuring assignment, you are effectively doing this:

const m = player.matrix;
const o = player.pos;

Note that this syntax is part of the ECMAScript 2015 (6th Edition, ECMA-262) standard and is not immediately available to all browser implementations. You can read more about it here.

There is also a compatibility table that you can check.

Gorka Hernandez
  • 3,412
  • 17
  • 27
  • Remove comma after `matrix` – Flying Oct 25 '17 at 10:21
  • Also note that the functionality of descructing assignments is only supported by [ECMAScript 6 or newer](https://kangax.github.io/compat-table/es6/#test-destructuring,_assignment) – Filnor Oct 25 '17 at 10:23
  • @chade_ Added note and link to official Ecma docs. Thanks. – Gorka Hernandez Oct 25 '17 at 10:27
  • How about in this case?: const [wordToReplace] = myArr.filter(item => item === before); – Netside Feb 24 '20 at 03:51
  • 1
    @Netside The 'wordToReplace' variable will now contain the first item in the resulting array. Consider starting a new question or searching for a similar one for a more complete answer though. – Gorka Hernandez Feb 25 '20 at 07:52