Start learning free

LESSON 605 OF 671 · PROJECTS: COMMAND-LINE TOOLS

head v3 in JavaScript: When n Is Larger Than the Input

Practice Read the full explanation

Same signature as v2, but now n may be larger than the number of lines. If n > lines.length simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.

Function signature:

head(lines, n)

Example:

Input: lines = ["alpha", "beta", "gamma"], n = 10

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

JavaScript's slice already handles the over-cap case. lines.slice(0, n) with n bigger than lines.length just returns all elements — no extra logic needed.

The full solution is identical to v2:
class Solution {
    head(lines, n) {
        return lines.slice(0, n).join("\n");
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in JavaScript, explained

    Problem overview

    The previous version of head(lines, n) assumed that n never exceeds the number of lines. This version drops that assumption: n can be larger than lines.length, and the method must then return all the lines. It must not crash and it must not pad the result. Here n is at least 0, and when n is 0 or there are no lines, the result is an empty string.

    For ["alpha", "beta", "gamma"] with n = 10, the result is "alpha\nbeta\ngamma".

    Approach: the code is already right

    The one line from the previous version, lines.slice(0, n).join("\n"), handles this case unchanged. This lesson is about why it works.

    slice(start, end) never reads past the end of the array. When end is bigger than the length, it behaves as if end were the length. So slice(0, 10) on three items returns the three items, with no undefined entries for the missing seven. Joining three items gives three lines and two newlines.

    The alternative is to compute the cap yourself with Math.min(n, lines.length) and slice up to that. For the five lines "a" to "e" and n = 8, both versions return "a\nb\nc\nd\ne". The explicit cap makes the intent visible, but it adds nothing to the result.

    Note what the answer does not do: it never invents lines. The result for a large n is the whole input, which is what the real head does when a file is shorter than the requested count.

    Step by step

    There is one step. Return lines.slice(0, n).join("\n"). Think of it as two independent guarantees. slice returns at most n items and never more than the array has. join turns any number of items, including none, into a string.

    The solution in JavaScript

    class Solution {
        head(lines, n) {
            return lines.slice(0, n).join("\n");
        }
    }

    Language details

    • Out-of-range indexes are handled differently by different array features. Reading lines[10] on a 3-item array gives undefined, while slice clamps its bounds and returns only what exists.
    • Even an infinite end works: slice(0, Infinity) on the five lines "alpha" to "epsilon" returns all five.
    • No new array is padded or extended. The result never has more items than the input.

    Using the method

    The method lives in a class, so the code that tests it creates an instance first and then calls it. After const s = new Solution();, the call s.head(["a", "b"], 5) returns "a\nb", and printing it shows a and b on two rows. Try it in the editor above and print the result with console.log, which shows the newlines as separate rows.

    Testing

    The method returns these results, where gr is the list ["alpha", "beta", "gamma", "delta", "epsilon"]:

    ["alpha","beta","gamma"], n = 10 -> "alpha\nbeta\ngamma"
    gr, n = 8 -> "alpha\nbeta\ngamma\ndelta\nepsilon"
    gr, n = 5 -> "alpha\nbeta\ngamma\ndelta\nepsilon"
    [], n = 4 -> ""
    gr, n = 0 -> ""

    Edge cases and common mistakes

    • Looping up to n. A for loop that reads lines[i] for i < n would collect undefined for a big n, and join would turn each one into an empty string. With n = 8 on five lines, the loop result is "a\nb\nc\nd\ne\n\n\n", with extra blank rows at the end. Looping to Math.min(n, lines.length) avoids that.
    • Adding a guard that isn't needed. A check such as if (n > lines.length) is harmless, but it duplicates what slice does.
    • Empty input. An empty array gives "" for any n.
    • n equal to the length. It is the boundary between the two versions, and it returns every line.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free