I don’t feel my needs spoiler tags around it, as it contains lots of breaks with text that would require someone read it in order to spoil it for them. This post is designed to be helpful, and not to just give the answer with no idea what is happening.
Here is line by line what your code is doing. I had to retype it all since I can’t copy from spoiler tags, so there might be a couple of typos. This is a challenge people have a hard time with, as it used newer concepts like embedded loops.
The code used is from comment #15
function findLongestWordLength(str) {
Basic function set up w/ a parameter. The desired input for str
is a senetnce and each word is seprated by a space. Lets say str
is "hello my name is"
var count = str.split(' ')
var longestWod = 0
count
is now a array and each item (element) in the array is a word.
["hello", "my", "name", "is"]
If you did .split('')
which has no space, then it would create an array where each element is a character. We don’t want this.
["h","e","l","l","o", ""]
(etc)
longestWord
is just a variable that will be used later. It needs to be declared outside the loop so you can reference it inside of the loop without resetting its value. For instance:
for (var i = 0; i < 5; i++) {
longestWord = "hello"
var longestWord = 0;
}
You can see that it would never hold the value "hello"
because it would be reset at the end of each loop.
for (var i = 0; i < count.length; i++) {
I want this loop to run as many times as count
is long. I start at 0 on the first loop because the index of an array starts at 0 for the first element. i
is the counter variable (CV) which is what I will be calling it from now on.
if (count[i].length > longestWord) {
count[i]
is how accessing my array with all my words and goes to the word that corresponds with my CV. When the CV is 0, then it will be count[0]
, which goes to the first word which is "hello"
.
So .length
will then get the length of that word/element which is 5. If my CV was 1, it would go to my second element of count
and get a length of 2 for “my”.
I then compare it to longestWord
which is a number and ask if it is greater then that. The default value is 0, so the first word/ element will always be bigger.
longestWord = count[i].length
Now if I compare the two and it is true, then I assign that length, 5 in the case of “hello” to longestWord
.
This then continues on for every word in the array until my CV is 5, and the loop ends and I return longestWord
, which is a number.
Have any questions? Please ask!