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 alphabet letter JavaScript
We are required to write a function that takes in a number between 1 and 26 (both inclusive) and returns the corresponding English alphabet for it. (capital case) If the number is out of this range return -1.
For example:
toAlpha(3) = C toAlpha(18) = R
The ASCII Codes
ASCII codes are the standard numerical representation of all the characters and numbers present on our keyboard and many more.
The capital English alphabets are also mapped in the ASCII char codes, they start from 65 and go all the way up to 90, with 65 being the value for 'A', 66 for 'B' and so on. We can use these codes to map our alphabets.
Example
const toAlpha = (num) => {
if(num < 1 || num > 26 || typeof num !== 'number'){
return -1;
}
const leveller = 64;
// since actually A is represented by 65 and we want to represent it with 1
return String.fromCharCode(num + leveller);
};
console.log(toAlpha(18));
console.log(toAlpha(1));
console.log(toAlpha(26));
console.log(toAlpha(0)); // out of range
console.log(toAlpha(27)); // out of range
Output
R A Z -1 -1
How It Works
The function uses String.fromCharCode() to convert ASCII codes to characters. Since 'A' has ASCII code 65 and we want to map number 1 to 'A', we add 64 (leveller) to our input number. This way:
- 1 + 64 = 65 ? 'A'
- 2 + 64 = 66 ? 'B'
- 26 + 64 = 90 ? 'Z'
Alternative Approach Using Array Index
const toAlphaArray = (num) => {
if(num < 1 || num > 26 || typeof num !== 'number'){
return -1;
}
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
return alphabet[num - 1]; // subtract 1 for 0-based indexing
};
console.log(toAlphaArray(3));
console.log(toAlphaArray(26));
Output
C Z
Conclusion
Both approaches work effectively. The ASCII method is more mathematical, while the array approach is more straightforward and readable for beginners.
