Start learning free

LESSON 603 OF 671 · PROJECTS: COMMAND-LINE TOOLS

head v1 in JavaScript: First 10 Lines with slice

Practice Read the full explanation

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

head(lines)

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Grab the first 10 elements of the array, then call join("\n") on the result. JavaScript's Array.prototype.slice is safe even when the array is shorter.

Use lines.slice(0, 10).join("\n") — slice caps the upper bound automatically.

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

STEP 1 OF 1
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Head V1 in JavaScript, explained

    Problem overview

    The Unix head command prints the beginning of its input, 10 lines by default. This first version builds that default as head(lines). The method receives an array of strings and returns the first 10 of them joined by newline characters. With fewer than 10 lines it returns all of them, and with no lines it returns an empty string.

    For the 13 lines "a" to "m", the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj", which prints as the letters a to j, one per row.

    Approach: slice, then join

    The task has two parts. The first is taking at most 10 items, and slice(start, end) does it. It returns a new array with the items from index start up to, but not including, index end. So lines.slice(0, 10) holds the items at indexes 0 to 9, which are the first 10.

    The second part is turning those items into text, and join("\n") does that, as in a cat tool: newlines go between lines, not after the last one.

    The "fewer than 10" rules need no code of their own. slice stops quietly at the end of the array when the end index is too big. It doesn't throw and it doesn't pad. Three lines give three items, and an empty array gives an empty array, which joins to "".

    The same result could come from a loop that copies lines one at a time until it has 10 or runs out, using Math.min(10, lines.length) as the bound. Both work, but the loop needs the bound to be right, while slice carries it inside the method. Because slice returns a copy, the caller's array is also left untouched.

    Step by step

    The lesson has one step. Return lines.slice(0, 10).join("\n"): slice first to keep the first 10 items, then join the result with newlines.

    The solution in JavaScript

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

    Language details

    • slice doesn't change the array it is called on. After head runs on the 13 letters, the array still has 13 items. (splice, a similarly named method, does modify its array.)
    • The end index is exclusive, so slice(0, 10) returns 10 items, not 11.
    • An end index past the array's length is allowed: alpha.slice(0, 20).length is 13 for the 13-letter array.

    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", "c"]) returns "a\nb\nc", because three lines are fewer than 10. 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 for inputs of different sizes:

    13 lines -> "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    exactly 10 lines -> "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    3 lines -> "a\nb\nc"
    0 lines -> ""

    Edge cases and common mistakes

    • Off by one. slice(0, 9) returns 9 items. The end index is the count when the start is 0.
    • Checking the length first. An if (lines.length < 10) branch is unnecessary, because slice already copes.
    • Forgetting join. Returning the sliced array gives an array, not the string the method promises.
    • The number 10 is fixed here. The next version builds on this one.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free