Start learning free

LESSON 77 OF 348 · CONDITIONAL STATEMENTS

Return Negative in TypeScript: if/else and Unary Minus

Practice Read the full explanation

Create a function that takes a number as an argument and returns negative of that number. Return negative numbers without any change.

Examples:

negative(4) ➞ -4

negative(15) ➞ -15

negative(-4) ➞ -4

negative(0) ➞ 0

Hints:

You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is positive.
STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · CONDITIONAL STATEMENTS

    Return Negative in TypeScript, explained

    Problem overview

    The method negative of the class Solution takes a number n and returns its negative. Numbers that are already negative are returned unchanged. So negative(4) is -4, negative(15) is -15, negative(-4) is -4 and negative(0) is 0.

    The result is therefore never a positive number. The only real decision is whether to flip the sign or leave the value alone.

    Approach

    Flipping the sign is the job of the unary minus: -n. If n is 4, -n is -4. If n is already -4, -n would be 4, which is the opposite of what we want. So the method needs a branch: when n is below zero it is already negative and is returned as it is, and in every other case the sign is flipped.

    That is a two-way choice, and if/else expresses it directly.

    Step by step

    1. Write the test first. The condition is n < 0, which is true exactly for negative numbers. Zero is not less than zero, so it goes to the other branch.
    2. Return n unchanged in the if block. A return ends the method right there and hands the value back to the caller.
    3. Return -n in the else block. This branch handles zero and every positive number, and for all of them the flipped sign is the answer.

    The solution in TypeScript

    class Solution {
        negative(n: number): number {
            if (n < 0) {
                return n;
            } else {
                return -n;
            }
        }
    }
    

    Some TypeScript details about this code:

    • The types. n: number declares the parameter and : number after the parentheses declares the return type. TypeScript's number covers integers and decimals alike, so the method works for -2.5 too. These annotations are checked by the compiler and erased from the JavaScript that runs.
    • Every path should return. If the method body is left empty, as in the starting code, the compiler reports A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value. The JavaScript still runs, but the method gives back undefined, not a number. Here both branches return, so nothing is missing.
    • Zero and negative zero. JavaScript numbers have a negative zero. negative(0) evaluates -n with n equal to 0, and the result is negative zero. It compares equal to zero (-0 === 0 is true), but console.log prints it as -0. Arithmetic and comparisons treat the two the same, so the difference only shows up when you print the value or test it with Object.is.

    Edge cases and common mistakes

    • Always returning -n. This works for positive numbers and breaks for negative ones: negative(-4) would give 4.
    • Using <= in the condition. With n <= 0, zero is returned unchanged, which also works. Either condition handles zero correctly. What matters is that negative inputs never reach -n.
    • Using n > 0 and swapping the branches. That is fine too, as long as the positive branch is the one that returns -n.
    • Forgetting a return in one branch. The caller receives undefined for the inputs that take that branch, and the compiler may not warn you.
    • Writing else with a condition. else (n >= 0) is a syntax error. Use else if (n >= 0) if you want a second test, but then the method has a path with no return, which is why the plain else is the better choice here.

    Testing

    const solution = new Solution();
    console.log(solution.negative(4));
    console.log(solution.negative(15));
    console.log(solution.negative(-4));
    console.log(solution.negative(-2.5));
    
    -4
    -15
    -4
    -2.5
    

    Zero is the interesting input. It goes to the else branch, and the method returns -0, which is equal to 0 under ===.

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free