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?
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.