Start learning free

LESSON 221 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Longest Word in JavaScript: Track the Best So Far

Practice Read the full explanation

Given an array of strings words, return the longest word: the one with the most letters.

If several words share the longest length, return the first of them.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: "pancakes"
Explanation: "pancakes" has 8 letters, more than "I" (1) and "love" (4).

Example 2:

Input: words = ["apple", "kiwi", "mango"]
Output: "apple"
Explanation: "apple" and "mango" both have 5 letters, the most. "apple" comes first, so it is the answer.

Example 3:

Input: words = ["code"]
Output: "code"
Explanation: With only one word, it is the longest.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • On a tie, the answer is the first of the longest words.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Longest Word in JavaScript, explained

    Problem overview

    The method longestWord(words) receives a non-empty array of strings and returns the word with the most letters. When several words tie for the longest length, the first of them wins.

    For ["apple", "kiwi", "mango"], "apple" and "mango" both have 5 letters. "apple" comes first, so the answer is "apple".

    Approach

    This is the "best so far" pattern. Keep a variable holding the longest word you have seen, and let each word try to replace it. After the last word has had its turn, the variable holds the answer.

    The variable needs a starting value. Because the array always has at least one word, the first word is a safe choice: before you look at anything else, it is the longest word seen. The loop then revisits it, which is harmless, since a word is never longer than itself.

    Step by step

    1. Store words[0] in longest, declared with let because it will change.
    2. Loop over the words with for...of.
    3. Compare lengths with word.length > longest.length. The strict > is what makes the first of equal-length words stay.
    4. Replace longest with word when it is longer.
    5. Return longest after the loop.

    Tracing the examples

    For ["apple", "kiwi", "mango"], longest starts as "apple". The first loop pass compares "apple" with itself: 5 is not greater than 5, so nothing changes. "kiwi" has 4 letters, which is not more than 5, so longest stays "apple". "mango" has 5 letters: a tie, and > is false for a tie, so "apple" stays and is returned.

    For ["I", "love", "pancakes"], longest becomes "I" at the start, then "love" when it is seen (4 is greater than 1), then "pancakes" (8 is greater than 4). Each replacement happens only when a word strictly beats the current leader, so the variable never moves to a shorter word.

    This is the same shape as finding a maximum number in an array. Only the measure changes: here the value being compared is word.length, while the thing being kept is the word.

    The solution in JavaScript

    class Solution {
        longestWord(words) {
            let longest = words[0];
            for (let word of words) {
                if (word.length > longest.length) {
                    longest = word;
                }
            }
            return longest;
        }
    }
    

    The function compares lengths but returns the word itself, a string. Keeping the word, rather than only its length, is what lets you return it at the end. Note that words[0] on an empty array would be undefined, and longest.length would then throw a TypeError. The lesson guarantees at least one word, so that case doesn't arise.

    Edge cases and common mistakes

    • Using >=. Each equal-length word would replace the previous one, so the last of the tied words would win. ["apple", "kiwi", "mango"] would return "mango".
    • Returning the length. The task asks for the word, not word.length.
    • Starting with an empty string. That also works for non-empty words, but starting from words[0] doesn't depend on any assumption about the letters.
    • One word. ["code"] returns "code": nothing is longer, so nothing replaces it.

    Testing

    • ["I", "love", "pancakes"] gives "pancakes".
    • ["apple", "kiwi", "mango"] gives "apple".
    • ["code"] gives "code".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free