ES6: Use Destructuring Assignment with the Rest Operator to Reassign Array Elements Why 2 const for arr?

Tell us what’s happening:

Your code so far

I have a problem, i.e. why are we accepting this below:


const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
  "use strict";
  // change code below this line
  const [a, b, ...arr] = list; // change this
  // change code above this line
  return arr;
}
const arr = removeFirstTwo(source);
console.log(arr); // should be [3,4,5,6,7,8,9,10]
console.log(source); // should be [1,2,3,4,5,6,7,8,9,10];

Instead of this:


const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
  "use strict";
  // change code below this line
  var a, b;
  [a, b, ...arr] = list; // change this
  // change code above this line
  return arr;
}
const arr = removeFirstTwo(source);
console.log(arr); // should be [3,4,5,6,7,8,9,10]
console.log(source); // should be [1,2,3,4,5,6,7,8,9,10];

My reason for the 2nd option is that I thought we cannot have 2 const variable with the same name. We’ve already initialised “const arr = removeFirstTwo(source);”, then why are we again initializing it here, “const [a, b, …arr] = list;”? Like, wouldn’t that supposed to give us an error for having two “const arr” ?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3808.0 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-operator-to-reassign-array-elements

The two variables exist in different scopes so they don’t conflict with each other.

1 Like