How to returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index in JavaScript : charCodeAt()

Java Script @ Freshers.in

The charCodeAt() method in JavaScript returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. UTF-16, the format many web pages and applications use, encodes each character as one or two 16-bit code units. The charCodeAt() method is an essential function within JavaScript’s string manipulation arsenal. It goes beyond mere textual representation, delving into the numeric Unicode values of characters, which is fundamental for certain tasks like encoding/decoding, sorting, and data transmission, especially in systems where Unicode values are paramount.

Syntax:

The syntax for charCodeAt() is simple and intuitive:

string.charCodeAt(index)

index: This parameter is the index of the character for which the UTF-16 code unit will be returned. The index starts from 0. If index isn’t provided or the number is out of range, charCodeAt() returns NaN.

Examples and execution:

The following examples can be directly executed in any JavaScript environment — this includes a browser’s developer console, online coding sandboxes, or a Node.js environment.

Basic usage:

let message = "hello";
let codeUnit = message.charCodeAt(0);
console.log(codeUnit); // Outputs: 104 (which is the Unicode code for "h")
No index provided:
let greeting = "Hi!";
let codeUnit = greeting.charCodeAt();
console.log(codeUnit); // Outputs: 72 (method assumes zero index if none is provided, which is "H")
Index out of range:
let phrase = "JavaScript";
let codeUnit = phrase.charCodeAt(100);
console.log(codeUnit); // Outputs: NaN (index is out of the range of the string characters)
Mapping characters to unicode:
function mapToUnicode(str) {
    for (let i = 0; i < str.length; i++) {
        console.log(`Character ${str.charAt(i)} is at index ${i} with Unicode ${str.charCodeAt(i)}`);
    }
}
let testString = "code";
mapToUnicode(testString);
// Outputs:
// Character c is at index 0 with Unicode 99
// Character o is at index 1 with Unicode 111
// Character d is at index 2 with Unicode 100
// Character e is at index 3 with Unicode 101
Comparing character codes:
function compareCodes(string1, index1, string2, index2) {
    let code1 = string1.charCodeAt(index1);
    let code2 = string2.charCodeAt(index2);

    if (code1 === code2) {
        console.log(`Characters at provided indices have the same Unicode: ${code1}`);
    } else {
        console.log(`Unicodes are different - String 1: ${code1}, String 2: ${code2}`);
    }
}
let firstString = "apple";
let secondString = "aardvark";
compareCodes(firstString, 0, secondString, 0); // Outputs: Characters at provided indices have the same Unicode: 97
Author: user