-1

What is the difference between the below two operations that accounts for the one with join resulting in "÷C " where the other with reduce results in "÷C"?

1

// returns "÷C "
["f7","43"].map(x=>'0x'+ x).map(String.fromCharCode).join('');

2

// returns "÷C"
["f7","43"].map(x=>'0x'+x).reduce((a, c) => { 
    a += String.fromCharCode(c); 
    return a 
}, '');
Community
  • 1
  • 1

1 Answers1

2

String.fromCharCode accepts multiple arguments. Each argument will be interpreted as a code unit. In the first code, since .map also provides arguments for the index and the array being iterated over:

["f7","43"].map(x=>'0x'+ x).map(String.fromCharCode).join('');

is equivalent to

["f7","43"]
  .map(x=>'0x'+ x)
  .map((str, i, arr) => (
    String.fromCharCode(str, i, arr)
  )
  .join('');

Which has unexpected results.

Explicitly pass only the str instead, and it'll result in the same as in the second snippet:

const result = ["f7","43"]
  .map(x=>'0x'+ x)
  .map((str) => (
    String.fromCharCode(str)
  ))
  .join('');
console.log(result);

(still, calling fromCharCode with something that isn't a number is weird and confusing, better to do it explicitly as Barmar mentions)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    he's depending on `fromCharCode()` converting the string to int, and doing it in hex because of 0x prefix – Barmar Apr 12 '20 at 02:04