Character code question

In this code:

if (code !== str.charCodeAt(0) + i) {
      /* if current character has escaped one character find previous char and return */
      return String.fromCharCode(code - 1);

Why are you adding i? That doesn’t make sense to be adding an iteration to a code value. I don’t get it.

Also what is String.fromCharCode(code - 1)?

Thanks

charCodeAt() returns a specific integer for each character.
(see: list of unicode characters)

let str = "abc";
console.log(str.charCodeAt(0)); // output: 97
console.log(str.charCodeAt(1)); // output: 98
console.log(str.charCodeAt(2)); // output: 99  

So adding something gives you an integer refering to later character and vice versa with subtracting.

1 Like

From what I can gather.

if (code !== str.charCodeAt(0) + i)

This line will finish executing when the code we’re looking for is equal to some Unicode value. As michael mentioned: charCodeAt() returns a specific integer for each character and we’re adding i to the same value each time: str.charCodeAt(0). So, I’m assuming here that i is being incremented by 1 each time.

The result is we get calls that are:
str.charCodeAt(0) + 0 = some number
str.charCodeAt(0) + 1 = some number

So, this code runs until code which is some number is equal to some unicode character that’s greater than or equal to the number returned from str.charCodeAt(0).

Once, we find the number that corresponds to code unicode value we execute:

Here, google is your best friend(or DuckDuckGo if you care about your privacy), “The fromCharCode() method converts Unicode values into characters.” So, it looks like what String.fromCharCode(code) would return the number that represents code unicode character. But, here we’re actually returning String.fromCharCode(code-1) which translated to plain old english is just the number that represents the unicode character before we hit code.

Unicode is a little confusing to deal with. But, as long as you can keep it clear in your head that these methods str.charCodeAt() and String.fromCharCode() are methods that deal with representing unicode characters as numbers you should be fine. It looks like this is what your principal confusing was on. We CAN add i to str.charCodeAt() because this method returns a number, therefore we can add things to it, subtract things from it, etc.

1 Like