-2

I read this post Use of [square brackets] around JavaScript variables, but I din't really get the idea why to use. This is the code I'm trying to understand:

let [translations] = await translate.translate(text, target);
translations = Array.isArray(translations) ? translations : [translations];

translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);

Can you help explaining me why the brackets in first line, and why the if statement in the second line?

asathkum
  • 174
  • 1
  • 15
Yuri Aps
  • 929
  • 8
  • 13
  • Destructuring, and ensuring an array. – Dave Newton Apr 17 '19 at 19:11
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment , https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/ – Tom O. Apr 17 '19 at 19:19
  • Possible duplicate of [Multiple assignment in javascript? What does \[a,b,c\] = \[1, 2, 3\]; mean?](https://stackoverflow.com/questions/3986348/multiple-assignment-in-javascript-what-does-a-b-c-1-2-3-mean) – Jordan Running Apr 17 '19 at 19:19
  • The post you linked to is not related to the syntax you're talking about. See the above linked question and answer. – Jordan Running Apr 17 '19 at 19:20
  • the first line is setting the expected results from the await call to be an array of transitions. The second line is ensuring it is an array that was returned, and if not, make it one. – Steven Stark Apr 17 '19 at 19:24

1 Answers1

2
let [translations] = await translate.translate(text, target);

The function translate.translate returns (a promise wrapped around) an array. The above is an equivalent of

let translationsArray = await translate.translate(text, target);
let foo = translationsArray[0];

Now, the second line:

translations = Array.isArray(translations) ? translations : [translations];

reads: "if translations is already an array, do nothing with it, if it's not, make an 1-element array out of it". So, at this point: ["cat", "dog"] remains unchanged, but "cat" becomes ["cat"].

mbojko
  • 13,503
  • 1
  • 16
  • 26