0

can some please explain why this function returns its original argument value instead of the altered value.

edit: FYI I know the solution to the problem already i just don't understand what is going on 'under the hood'; what is causing this not to work. i want better understanding of the language

function helper(value){
  let hold = value;
    hold.replace(/[^\w]/g, '')
    hold.split('')
    hold.sort()
    hold.join('')
    hold.toLowerCase()

    return hold
}

console.log(helper('hello world')) <--- returns 'hello world'
mayo19
  • 647
  • 8
  • 16
  • all functions written here, return value but won't change it unless it is assigned back to that variable. – Vivek Jun 02 '18 at 15:12
  • Possible duplicate of [JS replace not working on string](https://stackoverflow.com/questions/12231644/js-replace-not-working-on-string) – Sebastian Simon Jun 02 '18 at 15:24
  • Please try using the [debugging capabilities](https://developer.mozilla.org/en-US/docs/Mozilla/Debugging/Debugging_JavaScript) of your browser. Simply calling the method doesn’t mutate the variable, therefore you’re not returning a string with any modifications. The only exception is `sort` which sorts arrays in-place. But since you’re not storing any result anywhere, even that is lost. – Sebastian Simon Jun 02 '18 at 15:27

3 Answers3

3

You need to reassign, the functions does not change the original value and needs to be re-assigned. You can also use dot operator to combine all the operations and shorten the code like following

function helper(value){
    return value.replace(/[^\w]/g, '').split('').sort().join('').toLowerCase();
}

console.log(helper('hello world')) 

Alternatively, you can correct your code like this

function helper(value){
  let hold = value;
  hold = hold.replace(/[^\w]/g, ''); // re-assign
  hold = hold.split(''); // re-assign
  hold.sort(); // sort updates hold - re-assignment not required
  hold = hold.join(''); // re-assign
  hold = hold.toLowerCase(); // re-assign
  return hold;
}

console.log(helper('hello world'))
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

replace doesn't modify input argument but returns a new string instead.

PeteH
  • 79
  • 6
0

I have found the solution as to "WHY" the code was acting the way it was. it is because Arrays and Objects are mutable, while strings and numbers and other primitives are immutable.

for more info read this blog What are immutable and mutable data structures?

and the solution was posted here by "Nikhil Aggarwal"

mayo19
  • 647
  • 8
  • 16