Start learning free

LESSON 129 OF 348 · LOOPS & CONDITIONALS

Print Positive and Negative in TypeScript: Fixing the Buggy Code

Practice Read the full explanation

Inside the code editor we've tried to write a function that takes an array nums as argument and for every number in the array:

  • prints "negative" if that number is less than zero

  • or prints the number itself, if the number is greater than or equal to zero

So when we called the function for [2, -12, 0, 4, -5, 3], we expected it to print:

2
negative
0
4
negative
3

but it seems like we made some mistakes because when we run our code, it produces this output:

positive
2
-12
0
positive
4
-5
positive
3

Assignment:

Your task is to fix our loop such that it will print the desired output.

STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS & CONDITIONALS

    Buggy Code Print Positive Negative in TypeScript, explained

    What the code is supposed to do

    The function printPositiveAndNegative goes through an array of numbers called nums and prints exactly one line per number. If the number is less than zero, the line is the word negative. Otherwise the line is the number itself, which covers both zero and the positive numbers.

    For [2, -12, 0, 4, -5, 3] the expected output is:

    2
    negative
    0
    4
    negative
    3
    

    The code you start with does something else:

    function printPositiveAndNegative(nums: number[]): void {
        for (const num of nums) {
            if (num > 0) {
                console.log("positive");
            }
            console.log(num);
        }
    }
    
    // Do not change this code:
    printPositiveAndNegative([2, -12, 0, 4, -5, 3]);
    

    It prints an extra line, positive, before every positive number, and it prints the negative numbers as they are. Your job is to fix the loop.

    What goes wrong

    There are two separate problems, and both come from the shape of the loop body.

    1. The condition picks the wrong group. The test num > 0 is true for positive numbers, so the special message goes to them, and it reads positive. The task wants the special message for numbers below zero, with the text negative. The condition should be num < 0.
    2. The last line always runs. The console.log(num) sits after the if block, not inside any branch, so it executes for every number. A number that already got its message prints a second line. The task wants one line per number: either the message or the number, never both.

    Follow the code on the first two values to see the effect. For 2, the condition is true, so positive is printed, and then the number 2. For -12, the condition is false, so only the number -12 is printed. The output starts positive, 2, -12, exactly as the bug report says.

    Why the choice must be either or

    Each number needs one of two outcomes, and they exclude each other. A plain if followed by an unconditional line does not express that: the second action happens regardless. The if/else statement does. The if branch runs when the condition is true, and the else branch runs when it is false, so exactly one of the two runs on every pass.

    Zero deserves a moment of thought. The task says numbers greater than or equal to zero are printed as they are. The test num < 0 is false for 0, so the else branch handles it, and 0 is printed. You do not need a separate check for it. Choosing the condition num < 0 puts the boundary in the right place.

    Fixing it step by step

    1. Flip the comparison. Change num > 0 to num < 0, so the first branch is for negative numbers.
    2. Change the message. Print "negative" instead of "positive".
    3. Move the number into an else. Put console.log(num) inside an else branch so it runs only when the number is not negative.
    4. Leave the loop and the call alone. The for...of loop already visits every element, and the call at the bottom must not change.

    The fixed code in TypeScript

    function printPositiveAndNegative(nums: number[]): void {
        for (const num of nums) {
            if (num < 0) {
                console.log("negative");
            } else {
                console.log(num);
            }
        }
    }
    
    printPositiveAndNegative([2, -12, 0, 4, -5, 3]);
    

    Some TypeScript details in this code:

    • for...of gives the values. In for (const num of nums), num is each element in turn. for...in would give the indices instead, as strings. Declaring num with const is fine because a fresh variable is created on each pass.
    • number[] is an array of numbers. The annotation is checked by the compiler and erased from the JavaScript it writes, so it cannot stop a caller from passing something else when the program runs.
    • One function, two kinds of output. Both console.log("negative") and console.log(num) print their argument on its own line. A string and a number look the same in the console.
    • Decimals are also number. Passing [-0.5] prints negative, because -0.5 is below zero. Zero and positive decimals print themselves.

    Common mistakes

    • Fixing the message but not the structure. Changing "positive" to "negative" while keeping num > 0 prints the word for the wrong numbers, and the unconditional print still doubles up the lines.
    • Using <=. With num <= 0, zero would print negative. Zero is not less than zero.
    • Two separate if statements. One for num < 0 and one for num >= 0 gives the right output, but it tests twice. else says it in one place.
    • Printing the word for zero. The task keeps zero as a number, so the expected output has a plain 0 in the third line.

    Testing

    • [2, -12, 0, 4, -5, 3] prints 2, negative, 0, 4, negative, 3.
    • [] prints nothing, because the loop body never runs.
    • [-1] prints negative.
    • [0] prints 0.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free