The challenge
Write longestWord(sentence) that returns the longest word. If there’s a tie, return the first one.
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
longestWord("I love programming in JavaScript")gives"programming"longestWord("cat dog")gives"cat"longestWord("hippopotamus")gives"hippopotamus"
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Split into words, then keep track of the best one so far.
Hint 2
Only replace the best word when the new one is strictly longer (>), so ties keep the first.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function longestWord(sentence) {
let best = "";
for (const word of sentence.split(" ")) {
if (word.length > best.length) best = word;
}
return best;
}
Learn what you need
This exercise uses what Grade 7: Arrays: Lists of Things teaches. Read those notes first if any of it is new.