Search code examples
javascriptarraysdestructuring

Destructuring with Rest Operator in Array: Grabbing Array elements as variables as well as capturing remaining array in JavaScript


I am looking to grab the first two positions in an array (sourceArr) and assign them to variables (p & k in the code here). The using the rest operator to give me the remainder of the array (arr19) in another array result. This code seems to work to grab the remainder just fine. But get a "Uncaught ReferenceError: p is not defined" for my attempt to grab the initial positions as variables.

Any hints on what I am doing wrong! I thought the const [ p, k, ...arr19] = listMe would have defined p and k ???

const sourceArr = [1,2,3,4,5,6,7,8,9,10]
function reassignFirstTwo(listMe) {
  const [ p, k, ...arr19] = listMe  // the p & k variables are grabbed, followed by the REST dots (...) to grab the remaining array elements.
  return (p)
  return (k)
  return arr19
}
const arr19 = reassignFirstTwo(sourceArr)
console.log(arr19)  // This gives the resulting array with the elements removed
console.log(sourceArr)  // This gives the original array
console.log(p)
console.log(k)

Solution

  • The first return in your function only returns the p variable value of 1 and skips the next two returns as it exits the function.

    The p and k are scoped to the function reassignFirstTwo so you cannot access it outside of that function as such. Which you are trying to access globally therefore you are getting Uncaught ReferenceError: p is not defined.

    You can return the three variables as an object from the reassignFirstTwo function, then destructure it where you call it to get in the variables arr19, p, k (new variables) using the object destructuring technique:

    const sourceArr = [1,2,3,4,5,6,7,8,9,10]
    function reassignFirstTwo(listMe) {
      const [ p, k, ...arr19] = listMe;  
      return {p, k, arr19}
    }
    const { arr19, p, k } = reassignFirstTwo(sourceArr)
    console.log({arr19, sourceArr, p, k});