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
Indexing numbers to alphabets in JavaScript
We are required to write a JavaScript function that takes in a number between the range [0, 25], both inclusive and returns the corresponding alphabet character.
Return Value
The function should return the corresponding alphabet for that number, where 0 = 'A', 1 = 'B', 2 = 'C', and so on.
Using String.fromCharCode() Method
The most common approach uses ASCII values. The ASCII value of 'A' is 65, so we add our number to get the corresponding character.
const num = 15;
const indexToAlpha = (num = 1) => {
// ASCII value of first character
const A = 'A'.charCodeAt(0);
let numberToCharacter = number => {
return String.fromCharCode(A + number);
};
return numberToCharacter(num);
};
console.log(indexToAlpha(num));
console.log("Index 0:", indexToAlpha(0)); // A
console.log("Index 25:", indexToAlpha(25)); // Z
P Index 0: A Index 25: Z
Using Array Mapping Method
Another approach uses a predefined alphabet string and accesses characters by index.
const indexToAlphaArray = (index) => {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return alphabet[index];
};
console.log(indexToAlphaArray(15)); // P
console.log(indexToAlphaArray(7)); // H
console.log(indexToAlphaArray(0)); // A
P H A
With Input Validation
Here's a more robust version with error handling for invalid inputs:
const safeIndexToAlpha = (index) => {
if (index < 0 || index > 25 || !Number.isInteger(index)) {
return "Invalid input: Please provide an integer between 0-25";
}
return String.fromCharCode(65 + index);
};
console.log(safeIndexToAlpha(15)); // P
console.log(safeIndexToAlpha(26)); // Invalid input
console.log(safeIndexToAlpha(-1)); // Invalid input
P Invalid input: Please provide an integer between 0-25 Invalid input: Please provide an integer between 0-25
Comparison
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
| String.fromCharCode() | Fast | Medium | Low |
| Array/String indexing | Fast | High | Higher (stores alphabet) |
Conclusion
Both methods work effectively for converting numbers to alphabet characters. The ASCII approach using String.fromCharCode() is more memory-efficient, while the array indexing method is more readable for beginners.
