Start learning free

LESSON 604 OF 671 · PROJECTS: COMMAND-LINE TOOLS

head v2 in JavaScript: First n Lines with slice(0, n)

Practice Read the full explanation

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.length. If n is 0 the result is the empty string.

Function signature:

head(lines, n)

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Same idea as v1, but the cap is now n instead of the constant 10. Take a slice of lines up to index n, then join with "\n".

lines.slice(0, n) returns the first n elements; chain .join("\n").

The full solution:
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 V2 in JavaScript, explained

    Problem overview

    The first version of head always returned 10 lines. This version takes the count as a parameter: head(lines, n) returns the first n lines joined by newline characters. For this version n is between 0 and lines.length, inclusive, and when n is 0 the result is an empty string.

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

    Approach: replace 10 with n

    The change from the first version is one word. The slice used to end at the fixed index 10, and now it ends at n. lines.slice(0, n) returns a new array holding the items at indexes 0 up to, but not including, n. That is exactly the first n items.

    The extra rules in the statement are guaranteed by the range of n, and the code handles them without any branches. When n is 0, slice(0, 0) is an empty array, and joining an empty array gives "". When n equals lines.length, the slice is a full copy, so every line is returned.

    A loop could build the same result: push lines[i] for each i from 0 to n - 1. That works while n stays within the length, which this version guarantees. Its weak point appears when n is too big, because the loop would read past the end of the array. slice doesn't have that weakness, so it is the better habit.

    Step by step

    There is a single step. Return lines.slice(0, n).join("\n"). slice keeps the first n lines and join puts a newline between each two of them, with none after the last.

    The solution in JavaScript

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

    Language details

    • The parameter list is now (lines, n), and the lesson's tests call it with two arguments.
    • If n is not a whole number, slice converts it by dropping the fraction: head(lines, 2.7) on the five lines above returns "alpha\nbeta". The lesson only uses whole numbers.
    • Passing n is what separates this method from the previous one: the count is no longer fixed inside the code, so the same method serves any request.
    • The method never modifies lines, because slice returns a copy.

    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"], 2) 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

    With the five lines above, the method returns:

    n = 3 -> "alpha\nbeta\ngamma"
    n = 0 -> ""
    n = 5 -> "alpha\nbeta\ngamma\ndelta\nepsilon"
    n = 1 -> "alpha"

    Edge cases and common mistakes

    • n = 0. The result is the empty string, not an array and not undefined.
    • n equal to the length. Every line comes back. The end index is exclusive, so n is the right end index and not n + 1 or n - 1.
    • Using slice(n). With one argument, slice keeps everything from index n to the end, the opposite of what is wanted.
    • Going beyond the assumption. This version promises nothing for an n larger than the number of lines. The next version looks at that case.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free