Start learning free

LESSON 608 OF 671 · PROJECTS: COMMAND-LINE TOOLS

wc -w in JavaScript: Counting Words in Lines

Practice Read the full explanation

Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.

Function signature:

countWords(lines)

Example:

Input: lines = ["hello world", "foo bar baz", ""]

Output: 5

The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.

Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.


Iterate over the lines, split on whitespace, and accumulate the count. Watch out for empty lines — they should contribute zero, not one.

Use line.trim().split(/\s+/).filter(x => x).length. The filter drops the empty token that split produces for empty strings.

The full solution:
class Solution {
    countWords(lines) {
        let total = 0;
        for (const line of lines) {
            const tokens = line.trim().split(/\s+/).filter(x => x);
            total += tokens.length;
        }
        return total;
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in JavaScript, explained

    Problem overview

    The method countWords(lines) is the word-count half of the Unix wc tool. It receives an array of strings and returns one integer: the number of words across all the lines. A word is a run of characters without spaces or tabs, so any amount of whitespace between words counts as a single separator, and whitespace at the start or end of a line is ignored.

    For ["hello world", "foo bar baz", ""] the lines contribute 2, 3 and 0 words, so the answer is 5. A line that is empty or holds only whitespace adds 0, and an empty array gives 0.

    Approach: split each line, then count the real pieces

    The natural plan is to handle one line at a time: turn the line into an array of words, add that array's length to a running total, and return the total at the end. The only difficulty is turning a line into words correctly.

    line.split(" ") is not enough. It cuts at every single space, so two spaces in a row create an empty piece, and tabs are not separators at all. The regular expression /\s+/ fixes both: \s matches any whitespace character (space, tab and others) and + means "one or more", so a whole run of whitespace is one cut.

    Two edge pieces remain. Leading whitespace makes split start with an empty string, which is why the line is trimmed first. And splitting an empty string does not give an empty array: it gives [""], one empty piece. The same happens for a line that is only spaces, once it has been trimmed. Filtering out the empty pieces turns those cases into 0 words.

    Step by step

    1. Create total with let and set it to 0. It is a running sum, so it must start at zero before any line is read.
    2. Loop over the lines with for...of. for (const line of lines) hands you each string directly, with no index to manage.
    3. Build tokens. Trim the line, split it on /\s+/, then keep only the pieces that are not empty with filter(x => x). An empty string is falsy, so the callback returns a falsy value for it and the filter drops it.
    4. Add tokens.length to total, still inside the loop, once per line.
    5. Return total after the loop, not inside it. A return inside the loop would stop after the first line.

    The solution in JavaScript

    class Solution {
        countWords(lines) {
            let total = 0;
            for (const line of lines) {
                const tokens = line.trim().split(/\s+/).filter(x => x);
                total += tokens.length;
            }
            return total;
        }
    }
    

    Details worth knowing:

    • const in for (const line of lines) is fine: each pass creates a fresh binding for the current line.
    • split with a regular expression is the reason tabs and repeated spaces are handled. Splitting on the string " " would give "a b".split(" ") equal to ["a", "", "b"], an empty piece in the middle.
    • The filter is not optional. For a blank line, "".split(/\s+/) is [""] and " ".trim().split(/\s+/) is [""] too. Without the filter each blank line would count as one word.

    Complexity

    Every character of every line is looked at a constant number of times (trimming, splitting, filtering), so the time is O(n), where n is the total number of characters. Each line's array of words is temporary, so the extra space is proportional to the longest line.

    Edge cases and common mistakes

    • Forgetting the filter. An empty line would then add 1 instead of 0.
    • Forgetting trim(). A line like " a b" would split into ["", "a", "b"]; the filter would rescue the count, but trimming first keeps the code clear about its intent.
    • Splitting on " " only. Tabs stay inside words and double spaces create phantom pieces.
    • Returning inside the loop, which stops at the first line.

    Testing

    linesresult
    ["hello world", "foo bar baz", ""]5
    [" a \t b ", " ", ""]2
    []0
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free