Search code examples
javascriptinput

Can you use String.fromCodePoint just like String.fromCharCode


I'm still learning JavaScript and practicing with getting input from a keyboard. I just learned about String.fromCodePoint and it seems (to me) to pick up everything that String.fromCharCode does.

Is String.fromCodePoint supported widespread by browsers and devices and if so, does it make String.fromCharCode obsolete, or is there a reason you would use String.fromCharCode instead sometimes?


Solution

  • fromCharCode is not obsolete yet, but it would be if it would be supported by all Browsers. However fromCharCode is about twice as fast as fromCodePoint

    • String.fromCodePoint() Not supported by Internet Explorer and Safari

    • String.fromCharCode() Supported since for ever, double as fast

    • The difference:

      Although most common Unicode values can be represented with one 16-bit number (as expected early on during JavaScript standardization) and fromCharCode() can be used to return a single character for the most common values (i.e., UCS-2 values which are the subset of UTF-16 with the most common characters), in order to deal with ALL legal Unicode values (up to 21 bits), fromCharCode() alone is inadequate. Since the higher code point characters use two (lower value) "surrogate" numbers to form a single character, String.fromCodePoint() (part of the ES6 draft) can be used to return such a pair and thus adequately represent these higher valued characters.