0

Trying to figure out why the spread operator is needed in the code below in order for it to produce a return. When I delete the ..., no return is produced.

function binaryAgent(str) {

  return String.fromCharCode(
    ...str.split(" ").map(function(char) {
      return parseInt(char, 2);
    })
  );
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
BillyG
  • 9
  • 3
  • The code is working for me without the spread operator – Tamir Abutbul Sep 27 '22 at 09:00
  • 6
    Because there's a difference between passing a single array parameter and passing separate parameters - [`fromCharCode`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode) expects the latter. Note `String.fromCharCode(NaN)` -> `'\x00'`, so that's what you get if you don't pass numbers. – jonrsharpe Sep 27 '22 at 09:00
  • 1
    @Tamir Abutbul: You get a difference by passing whitespace separated strings. – Lain Sep 27 '22 at 09:01
  • 1
    @jonrsharpe shouldn't this be an answer instead? – jperl Sep 27 '22 at 09:05
  • @BillyG the comment of jonrsharpe and the reasoning why it's then a duplicate get's a bit more clear , if you first determine the intermediate array and save it in an extra variable: `const arr = str.split(" ").map(f);` and only then you want to spread the entries of this array into the arguments of the function `String.fromCharCode()`, so you need the spread operator `String.fromCharCode(...arr)` – Sebastian Sep 27 '22 at 09:27

0 Answers0