Javascript Function that returns true if a letter?

You could just use a case-insensitive regular expression:

var isAlpha = function(ch){
  return /^[A-Z]$/i.test(ch);
}

If you are supposed to be following the instructions in the comments about greater than and less than comparisons, and you want to check that the input is a string of length 1, then:

var isAlpha = function(ch){
  return typeof ch === "string" && ch.length === 1
         && (ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z");
}

console.log(isAlpha("A"));      // true
console.log(isAlpha("a"));      // true
console.log(isAlpha("["));      // false
console.log(isAlpha("1"));      // false
console.log(isAlpha("ABC"));    // false because it is more than one character

Expand snippet

You’ll notice I didn’t use an if statement. That’s because the expression ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" evaluates to be either true or false, so you can simply return that value directly.

What you had tried with if (ch >= "A" && ch <= "z") doesn’t work because the range of characters in between an uppercase “A” and a lowercase “z” includes not only letters but some other characters that are between “Z” and “a”.

Leave a Comment