0

I am looking to find out what type of function it is in JavaScript that modifies the original variable, as shown below.

let array = ["a", "b", "c"]
console.log(array) // Returns: ["a", "b", "c"]
array.shift()
console.log(array) // Returns: ["b", "c"]

With other functions, you would normally have to do the following.

let string = " String "
console.log(string) // Returns: " String "
string.trim()
console.log(string) // Returns: " String "
string = string.trim()
console.log(string) // Returns: "String"

How would I reproduce the same type of function?

Levi_OP
  • 945
  • 1
  • 9
  • 22
  • so you want a shift that does not modify the array on which you are invoking shift? – Alberto Sinigaglia Jul 22 '20 at 23:46
  • @Berto99 no, i want to make my own function that modify the variable it is invoking, a string maybe. Any example would be helpful. – Levi_OP Jul 22 '20 at 23:50
  • This may help: https://lorenstewart.me/2017/01/22/javascript-array-methods-mutating-vs-non-mutating/ – jdaz Jul 22 '20 at 23:50
  • @Berto99 ... no, OP asks for a mutating variant of `trim` similar to `shift` that mutates its array. – Peter Seliger Jul 22 '20 at 23:51
  • @jdaz Thanks! That is very helpful. But I was wondering if there was any way I could make my own? – Levi_OP Jul 22 '20 at 23:52
  • 2
    Ah got it. You cannot modify passed variables that are primitives, like numbers or strings. You can only change arrays or objects. See this answer: https://stackoverflow.com/a/3638034/1174966 – jdaz Jul 22 '20 at 23:55
  • @jdaz This is what i was looking for. Thanks! – Levi_OP Jul 23 '20 at 00:03

0 Answers0