1

So I wanted to swap the first and the last items of an array with the destructuring assignment. I tried using the ES2022 method array.at() to get the values of indexes:

const array = ['a, 'i', 'r'];
[array.at(0), array.at(-1)] = [array.at(-1), array.at(0)];

But when I run this, the SyntaxError is printed out to the console:

[array.at(0), array.at(-1)] = [array.at(-1), array.at(0)];
 ^^^^^^^^^^^

SyntaxError: Invalid destructuring assignment target
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)

I then changed the array.at() methods to classic array[] and now the swapping works correctly without any errors:

[array[0], array[array.length - 1]] = [array[array.length - 1], array[0]];

console.log(array); // ['r', 'i', 'a']

Could someone tell me what the problem with swapping with destructuring assignment using array.at() might be?

Caesar
  • 41
  • 6
  • 2
    The difference is that `array.at(0) = 1` does not work, but `array[0] = 1` does. – t.niese Feb 25 '23 at 12:37
  • 3
    `array.at()` is just a function call. JavaScript has no concept of pointers or references (not in this sense anyway), so assigning to the return value of a function doesn't make sense, and as such it is not valid. So, `array.at()` can only be used to read an array element, but not to write it. – FZs Feb 25 '23 at 12:40
  • 1
    as the comment above says you cannot a new assign value using at – cmgchess Feb 25 '23 at 12:41

1 Answers1

1

It is not valid to assign a value to a function call:

function sayHey() {
  return 'Hey';
}

sayHey() = 'Hello'; // ReferenceError: Invalid left-hand side in assignment

P.S. Thanks to FZs from comments for explaining this.

Caesar
  • 41
  • 6