0

I try to understand a conceptual difference between:

var x = '8aaaaa dddd r     '

function noSpace(x){
  return (x.split(" ").join(""));
}
noSpace(x) //Results in "8aaaaaddddr"

AND

var x = '8aaaaa dddd r     '

function noSpace(x){
  x.split(" ").join("");
  return x;
}

noSpace(x) //Results in "8aaaaa dddd r     "

Why does the second version don't work as the first one?

  • Primitives are immutable. If a variable name holds a primitive value, that variable name will always continue to reference that same primitive value unless explicitly reassigned. Only with objects can you see side-effects to some variable without explicit reassignment – CertainPerformance Sep 06 '19 at 08:15
  • `'splice' !== 'split'`. btw, no need to wrap the value for `return`. – Nina Scholz Sep 06 '19 at 08:15
  • `split` and `join` return the split or joined string and do not update the value of `x` directly – phuzi Sep 06 '19 at 08:16
  • 2
    As @CertainPerformance said, 2nd case does practically nothing. You have to do smth like `x = x.split(" ").join("");` – Pavel Třupek Sep 06 '19 at 08:17
  • thx @PavelTřupek that helped me most to understand the concept – Stephan - the curious Sep 06 '19 at 08:19
  • @NinaScholz yeah, because splice is for arrays, right? Or did you want me to tell anything else? – Stephan - the curious Sep 06 '19 at 08:21
  • @user2132380, i refer to the subject and the code and a possible mixup. `slice` and `split` are methods of `String` as well as `slice` and `splice` are methods of `Array`. both features `slice` with same parameters. – Nina Scholz Sep 06 '19 at 08:24
  • It's impossible to change a primitive in-place, as referenced in a number of places in the link. There's probably a better dupe link around, this sort of question isn't uncommon – CertainPerformance Sep 06 '19 at 08:26

0 Answers0