Solution to String Exercise 1

Here's my clever solution to this exercise. As always, dozens of ways exist to solve this problem, and the solution you consider "best" depends on your sense of art, need for efficiency, love of clarity, and what you had for lunch.

<script language="JavaScript">
<!-- hide me

// this function determines if the last letter of
// a word is a vowel or consonant
//
function vowel_or_what()
{
    var vowels = "aeiou";
    var the_word = prompt("what's the word?","");
    var last_letter = the_word.charAt(the_word.length-1);

    // if last_letter isn't in the vowels string it's a consonant

    if (vowels.indexOf(last_letter) == -1)
    {
        alert(the_word + "ends in a consonant!");

    } else {

       alert(the_word + "ends in a vowel!");
    }
}

// show me -->
</script>

I'm just showing you the function here. You should know by now how to call it from within a link.

The first thing I do in the function is define a string that contains each of the vowels. I'm leaving out "y" just to keep things simple (and to bug the linguistic purists out there ... ha ha).

Then, I use the prompt box to ask the user for a word, and I use the charAt method just described to find what the last letter of the word is. Now that I have the last letter, I can use indexOf to see if it's in the string of vowels. Neat, eh? If it's not in the string of vowels, then it's a consonant.

I could have used a big boolean test to see if the last letter was a vowel by doing something like this:

if ((last_letter == 'a') ||
(last_letter == 'e') || (last_letter == 'i') ||
	(last_letter == 'o') ||
(last_letter == 'u'))
{
	alert("it's a vowel");
} else {

	alert("it's a consonant");
}

But that's sort of bulky and messy. It's also easier to figure out what's going on, so some might choose that course in the name of legibility. As I said, which you choose depends on lots of factors.