Mutate an Array Declared with const

Mutate an Array Declared with const
0

#1

Tell us what’s happening:

Can someone tell me, what is the wrong in this code ? The output throws an error, “s should be equal to [2, 5, 7]”

Your code so far


const s = [5, 7, 2];
function editInPlace() {
  "use strict";
  // change code below this line

   s.push('s.pop()');
  console.log(s);
  // change code above this line
}
editInPlace();

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const/


#2
s.push('s.pop()');

What do you think this is going to do?


#3

I expect that it will pop the item ‘2’ from const ‘s’ and then push it again to const ‘s’ at index 0.

ref:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

#4

Good on you for using array methods. There’s a few problems with that, though.

  1. “The push() method adds one or more elements to the end of an array” [1]
  2. String values are not executed code, so a function call wrapped in quotes won’t do anything.
's.pop()'// Just a string
s.pop() // This will call the function

Read the instructions carefully for how to solve this challenge.


#5

Ah, I blindly read that line [1 The push() method adds one or more elements to the end of an array ]

s.unshift(s.pop); // this is working correctly

Thanks @PortableStick