I keep getting an infinite loop and don't understand why my code doesn't work and keeps crashing the browser.
<!DOCTYPE html>
<html>
<body>
<script>
function firstLetter(word, letter) {
var firstLetter = "";
while(word.indexOf(" ", letter) !== -1) {
letter = word.indexOf(" ") + 1;
console.log(word.charAt(letter));
}
return firstLetter;
}
console.log(firstLetter('Hi!, my name is Jessica.'));
</script>
</body>
</html>
There's no way out of your
while
loop. It keeps finding the first space in the string, continuously, forever, becauseletter = word.indexOf(" ")
will only ever find the first space. You should remember the value you got from the call toindexOf
in the loop (while ((letter = word.indexOf(" ", letter)) !== -1)
) rather than using a second call, so it picks up where you left off and you work your way through the string. You should also defaultletter
when it's not supplied (letter = letter || 0;
at the beginning will do for this function; that setsletter
to0
if it has any falsy* value).Alternately, you'd use
split
and then take the first letter of each entry.Note that I'm not providing explicit code as I figure this is a learning exercise.
Separately, you probably want to add to
firstLetter
in the loop.* "falsy" - JavaScript has "falsy" values (values that coerce to
false
when used as booleans) and "truthy" values (ones that coerce totrue
when used as booleans). The falsy values areundefined
,""
,0
,NaN
,null
, and of course,false
. All others are truthy. When you don't supply an argument for a parameter when calling a function, the parameter gets the valueundefined
.