0

I wanted to pass an array of number to the method String.fromCharCode(), I read another thread and tried to chain apply after fromCharCode, but it doesn't work for me. Here's the code:

function rot13(str) {
  var reStr = "";
  var asciiCodedArr = [70,82,69,69,32,67,79,68,69,32,67,65,77,80];
  reStr = String.fromCharCode().apply(null, asciiCodedArr);
  return reStr;
}

rot13("SERR PBQR PNZC");

And it yells back at me:

TypeError: String.fromCharCode(...).apply is not a function

Where did I mess up ?

Community
  • 1
  • 1
  • 2
    You are calling apply on the invocation of the function instead of the function. Use: `String.fromCharCode.apply(null, asciiCodedArr);` – Niklas Mar 07 '17 at 03:10
  • `apply` is a property of functions; you're trying to call it on the _result_ of the `fromCharCode` function. Try `String.fromCharCode.apply` without the parens – Hamms Mar 07 '17 at 03:10

2 Answers2

1

Remove the () after fromCharCode, and you're golden.

Essentially, you were trying to find an apply method on the result of calling fromCharCode (which is a string and thus does not have methods from Function.prototype) instead of on the function fromCharCode itself.

function rot13(str) {
  var reStr = "";
  var asciiCodedArr = [70, 82, 69, 69, 32, 67, 79, 68, 69, 32, 67, 65, 77, 80];
  reStr = String.fromCharCode.apply(null, asciiCodedArr);
  return reStr;
}

console.log(rot13("SERR PBQR PNZC"));
gyre
  • 16,369
  • 3
  • 37
  • 47
0

Remove ()

 reStr = String.fromCharCode.apply(null, asciiCodedArr);

NOT

 reStr = String.fromCharCode().apply(null, asciiCodedArr);
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254