Finding alphabet from ASCII value without using library functions in JavaScript

Problem

We are required to write a JavaScript function that takes in a number representing an ASCII value. Our function should return the corresponding alphabet character for that ASCII value (if it exists), or -1 otherwise.

The condition here is that we cannot use any built-in function like String.fromCharCode() that directly converts ASCII values to characters.

Understanding ASCII Values

ASCII values for alphabetic characters follow these ranges:

  • Uppercase letters: A-Z have ASCII values 65-90
  • Lowercase letters: a-z have ASCII values 97-122

Example

Following is the code:

const num = 98;

const findChar = (num = 1) => {
    const alpha = 'abcdefghijklmnopqrstuvwxyz';
    
    // Check for lowercase letters (97-122)
    if(num >= 97 && num <= 122) {
        return alpha[num - 97];
    }
    
    // Check for uppercase letters (65-90)
    if(num >= 65 && num <= 90) {
        return alpha.toUpperCase()[num - 65];
    }
    
    // Return -1 if not an alphabet ASCII value
    return -1;
};

console.log(findChar(num));
b

Testing Multiple Values

Let's test the function with different ASCII values:

const findChar = (num = 1) => {
    const alpha = 'abcdefghijklmnopqrstuvwxyz';
    
    if(num >= 97 && num <= 122) {
        return alpha[num - 97];
    }
    
    if(num >= 65 && num <= 90) {
        return alpha.toUpperCase()[num - 65];
    }
    
    return -1;
};

// Test various ASCII values
console.log("ASCII 65:", findChar(65));  // A
console.log("ASCII 90:", findChar(90));  // Z
console.log("ASCII 97:", findChar(97));  // a
console.log("ASCII 122:", findChar(122)); // z
console.log("ASCII 48:", findChar(48));   // -1 (digit '0')
console.log("ASCII 32:", findChar(32));   // -1 (space)
ASCII 65: A
ASCII 90: Z
ASCII 97: a
ASCII 122: z
ASCII 48: -1
ASCII 32: -1

How It Works

The solution uses string indexing to map ASCII values to characters:

  • For lowercase letters: alpha[num - 97] maps ASCII 97-122 to indices 0-25
  • For uppercase letters: alpha.toUpperCase()[num - 65] maps ASCII 65-90 to indices 0-25
  • Returns -1 for non-alphabetic ASCII values

Conclusion

This approach successfully converts ASCII values to alphabet characters without using built-in conversion functions. It leverages string indexing and arithmetic to map ASCII ranges to array indices.

Updated on: 2026-03-15T23:19:00+05:30

545 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements