Abdo77
December 4, 2022, 5:31pm
1
I have solved the challenge but I want to understand this code
function findLongestWordLength(str) {
let longestLength = 0;
let currentLength = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === " ") {
if (currentLength > longestLength) {
longestLength = currentLength;
}
currentLength = 0;
} else {
currentLength++;
}
}
if (currentLength > longestLength) {
longestLength = currentLength;
}
return longestLength;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
My main question is how does the code knows that it compares a hole word and not just a latter
Rather then explain every line, could you let us know what is vexing you?
1 Like
Abdo77
December 4, 2022, 5:34pm
3
Hi Kevin
My main question is how does the code know that it compares a whole word and not just a letter
You designed a solution, right? What was your big picture plan here? This code is executing that plan.
The heart of the loop handles work breaks.
Abdo77
December 4, 2022, 5:51pm
5
I know that the loop handles work breaks, which is what I did in my solution, but in my solution, I used regex to break the sentence into an array of words (split can be used to do the same job ) in this code, it does the same functionality and it does not split the sentence I am missing out how the letters become words
Figuring out how code works is an important skill. Try logging stuff out and see if you can figure it out:
function findLongestWordLength(str) {
let longestLength = 0;
let currentLength = 0;
for (let i = 0; i < str.length; i++) {
console.log('*** loop', i, str[i])
console.log('longestLength', longestLength)
console.log('currentLength', currentLength)
if (str[i] === " ") {
if (currentLength > longestLength) {
longestLength = currentLength;
}
currentLength = 0;
} else {
currentLength++;
}
}
if (currentLength > longestLength) {
longestLength = currentLength;
}
return longestLength;
}
console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
Abdo77
December 4, 2022, 6:07pm
8
@kevinSmith
ok, will do thank you Kevin
Abdo77
December 4, 2022, 6:12pm
9
@JeremyLT
exactly the currentLength is reset to zero if not greater than longestLength and why does it contain a number of letters and not a single letters
Current length is always set to zero when a space is found.
1 Like
Abdo77
December 4, 2022, 6:35pm
12
@kevinSmith
Thank you so much Kevin Your code helped me understand, the debugging was so professional that it made every step clear to me.
Abdo77
December 4, 2022, 6:40pm
13
@JeremyLT
Thank you very much, Jeremy, I can see that now if I could take two answers as the solution it would be both your’s and Kevin’s
This is a good problem for showing off that there is a variety of syntax that basically expresses the same logic.
system
Closed
June 5, 2023, 6:47am
15
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.