3

Take this code:

var charCode = unkownVariable.charCodeAt(0);

What is the max length that charCode can be? All my tests turned out as 2 character (2 digits). Will it ever be longer?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Nathan J.B.
  • 10,215
  • 3
  • 33
  • 41

3 Answers3

4

From the specification:

Returns a Number (a nonnegative integer less than 216) representing the code unit value of the character at position pos in the String resulting from converting this object to a String. If there is no character at that position, the result is NaN.

So, 216 - 1 is the maximum value, which is 65535.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Interesting. So the smallest, single-byte representation of the highest character code (with native JS decode support) would be: `1ekf` (`(65535).toString(36)`) – Nathan J.B. Mar 21 '13 at 17:19
  • Is there any way, we can access this 2^16 - 1 (the maximum value, which is 65535) ? For example, for numbers we have Number.MAX_VALUE. Thanks in advance. – Rashmi Jul 13 '22 at 08:13
  • @Rashmi: I'm not aware of a built-in constant representing that value, but if you know it then you can create your own constant. – Felix Kling Jul 13 '22 at 09:03
1

Short answer: yes.

var unkownVariable = 'test';
var charCode = unkownVariable.charCodeAt(0);
console.log(charCode); // 116

There are 16 bits used to display characters (there are different languages and charsets to consider), so the response theoretically could be anywhere between 0 and 65536 (2^16).

CWSpear
  • 3,230
  • 1
  • 28
  • 34
1

MDN says

Note that charCodeAt will always return a value that is less than 65,536.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt

Aaron Kurtzhals
  • 2,036
  • 3
  • 17
  • 21