Beginner learner in Javascript here! I am doing a few exercises based on do-while loops. As with my other questions (this is my 2nd one!) while I am learning, I always try to challenge my curiosity. The exercise asked me to do come up with this code, which is works based on the criteria of the exercise:
var i = 0;
var animals = ["horse", "ox", "cow", "pig", "duck"];
do {
if (animals[i] === "pig") {
alert(animals[i] + " is at Index " + i + "!");
break;
}
i++;
} while (i < animals.length);
But I wanted to see if I could deliver it in a much more "user-friendly" and "proper way" to displaying the alert in which the first letter of the string would be capitalized. Of course, I know that I could have just capitalized the strings in the array but I wanted to challenge myself in making JS convert to strings in the array to a capitalized first letter in the alert, so I came up with this, which works when I ran it on jsfiddle:
var animals = ["horse", "ox", "cow", "pig", "duck"];
var i = 0;
do {
if (animals[i] === "pig") {
var firstChar = animals[i].slice(0,1);
var otherChars = animals[i].slice(1);
firstChar = firstChar.toUpperCase();
otherChars = otherChars.toLowerCase();
var properAnswer = firstChar + otherChars;
alert(properAnswer + " is at Index " + i + "!");
break;
}
i++;
} while (i < animals.length);
Now my question is, is there a way to simplify the code above?
Sorry if my question was long >< I wanted to set it up so you can understand my context! Thank you in advance!