Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert number to characters in JavaScript
In JavaScript, converting numbers to characters is commonly done using ASCII/Unicode values. JavaScript provides the built-in String.fromCharCode() method to convert numeric values to their corresponding characters.
The String.fromCharCode() Method
The String.fromCharCode() method converts Unicode values to characters. Each number represents a specific character in the ASCII/Unicode table.
Syntax
String.fromCharCode(num1, num2, ..., numN)
Example: Single Number to Character
const n = 65;
const c = String.fromCharCode(n);
console.log(c);
console.log("Number 72 becomes:", String.fromCharCode(72));
console.log("Number 101 becomes:", String.fromCharCode(101));
A Number 72 becomes: H Number 101 becomes: e
In this example, 65 corresponds to 'A', 72 to 'H', and 101 to 'e' in the ASCII table.
Converting Multiple Numbers
You can convert multiple numbers at once by passing them as separate arguments:
const result = String.fromCharCode(72, 101, 108, 108, 111); console.log(result);
Hello
Converting an Array of Numbers
For arrays, you can use a loop or the spread operator:
// Method 1: Using for loop
const numArray = [68, 69, 70];
let chars = "";
for (let i = 0; i < numArray.length; i++) {
chars += String.fromCharCode(numArray[i]);
}
console.log("Using loop:", chars);
// Method 2: Using spread operator
const nums = [87, 111, 114, 108, 100];
const word = String.fromCharCode(...nums);
console.log("Using spread:", word);
Using loop: DEF Using spread: World
Common ASCII Values
| Number | Character | Type |
|---|---|---|
| 65-90 | A-Z | Uppercase letters |
| 97-122 | a-z | Lowercase letters |
| 48-57 | 0-9 | Digits |
| 32 | Space | Whitespace |
Practical Example: Creating a Message
const secretCode = [74, 97, 118, 97, 83, 99, 114, 105, 112, 116];
const message = String.fromCharCode(...secretCode);
console.log("Decoded message:", message);
// Verify each character
secretCode.forEach((num, index) => {
console.log(`${num} -> ${String.fromCharCode(num)}`);
});
Decoded message: JavaScript 74 -> J 97 -> a 118 -> v 97 -> a 83 -> S 99 -> c 114 -> r 105 -> i 112 -> p 116 -> t
Time Complexity
Converting a single number has O(1) time complexity. Converting an array of n numbers has O(n) time complexity due to iteration through the array elements.
Conclusion
Use String.fromCharCode() to convert numbers to characters in JavaScript. For multiple numbers, the spread operator provides a clean, efficient solution compared to loops.
