Exercise 7: Find Longest Word in Sentence

Problem Statement

Create a function `longestWord(sentence)` that returns the longest word from sentence. Example: longestWord("The quick brown fox") → "quick"

Sample Output:

longestWord("The quick brown fox") => "quick"
longestWord("Hello World") => "Hello"

Solution

const longestWord = (sentence) => {
  const words = String(sentence ?? "").trim().split(/\s+/);
  if (words.length === 0 || words[0] === "") return "";
  return words.reduce((longest, word) => word.length > longest.length ? word : longest, words[0]);
};

Explanation

Overall Goal:

  • Sentence me se sabse lamba word find karna.

Line 1: Function header

  • const longestWord = (sentence) => {

Line 2: Split into words

  • const words = String(sentence ?? "").trim().split(/\s+/);
  • Split by whitespace.

Line 3: Edge case

  • if (words.length === 0 || words[0] === "") return "";

Line 4: Find longest

  • return words.reduce((longest, word) => word.length > longest.length ? word : longest, words[0]);
  • Reduce se compare karke longest find.

Real world:

  • Text analysis: content analysis.
  • Search: keyword extraction.