ES6 - Mutate an Array Declared with const

Tell us what’s happening:
I successfully completed this challenge. I included some quality checks using console log and there is a quirk. I’m wondering why the console prints:
“Unshifted 3”, instead of “Unshifted 2”?

Your code so far

const s = [5, 7, 2];
function editInPlace() {
  // Only change code below this line
  let Popped = s.pop();
  console.log(s);
  console.log("Popped " + Popped);
  // Using s = [2, 5, 7] would be invalid
  let Unshifted = s.unshift(Popped);
  console.log(s);
  console.log("Unshifted " + Unshifted);
  // Only change code above this line
}
editInPlace();

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

Challenge: ES6 - Mutate an Array Declared with const

Link to the challenge:

Read about the Return value of unshift here. It is the same Return value returned from the push method.

1 Like

Oh. Interesting. It returns the array length. I played with the array values and lengths and confirm this. Thank you!
I made a small change in my last console.log

console.log("Repositioned the popped value: " + Popped);

Just adding other details that you may find interesting:

  • unshift is kind of opposite to push, both return length
  • shift is kind of opposite to pop, both return an element (first or last, respectively.)

All of these Array methods mutate the array.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.