Start learning free

LESSON 77 OF 410 · CONDITIONAL STATEMENTS

Return Negative in JavaScript: if/else and the 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:

4 ➞ -4

15 ➞ -15

-4 ➞ -4

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 not negative.
STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · CONDITIONAL STATEMENTS

    Return Negative in JavaScript, explained

    Problem overview

    The method negative(n) takes a number and returns its negative. A positive number is flipped: negative(4) is -4 and negative(15) is -15. A number that is already negative is returned unchanged: negative(-4) is -4. Zero is the boundary case, and it is neither positive nor negative: negative(0) gives zero.

    The trap is the already-negative input. Writing return -n; on its own would turn -4 into 4, because negating a negative number gives a positive one. The function needs to look at the sign first.

    Approach

    There are two kinds of input, so the code needs two paths:

    • If n is less than 0, it is already negative. Return it as it is.
    • Otherwise n is zero or positive. Return -n, the number with its sign flipped.

    The minus sign in front of a single value is the unary minus operator. It flips the sign of its operand: -n is -4 when n is 4, and -n is 4 when n is -4. That second behavior is why the check comes first.

    Step by step

    1. Test the sign. Write an if with the condition n < 0. When it is true, the input is already negative.
    2. Return n unchanged inside that branch.
    3. Add an else branch that returns -n. It runs for zero and for every positive number, which is exactly when the sign needs flipping.

    The solution in JavaScript

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

    Only one branch runs for any given input, and both end in return, so the method always returns a value. Here is how it handles the lesson's examples:

    CallCondition n < 0Result
    negative(4)false-4
    negative(15)false-15
    negative(-4)true-4
    negative(0)false0 (really -0, see below)

    Shorter ways to write it

    The same logic fits in one line with the conditional operator: return n < 0 ? n : -n;. Another option is -Math.abs(n). Math.abs removes the sign, so its result is never negative, and the unary minus in front of it makes the result negative or zero for every input. All three versions return the same numbers for the lesson's examples. The if/else form is the clearest while you are learning conditionals.

    Negative zero

    JavaScript numbers can hold a negative zero, written -0. Since 0 < 0 is false, negative(0) goes to the else branch and returns -0, the negation of zero. It behaves like zero in almost every way:

    const result = new Solution().negative(0);
    console.log(result === 0);          // true
    console.log(result == 0);           // true
    console.log(Object.is(result, -0)); // true
    console.log(`${result}`);           // 0
    console.log(result);                // -0
    

    The comparison === treats -0 and 0 as equal, which is why the lesson's test for negative(0) accepts this solution. Only Object.is and a few outputs, such as printing the number directly in the console, tell them apart. If you want a plain 0, return n for both zero and negatives by checking n <= 0 instead.

    Related questions

    How do I make a negative number positive in JavaScript?

    Use Math.abs(n). It returns n for positive numbers and flips the sign of negative ones, so Math.abs(-7) is 7 and Math.abs(7) is also 7. If you already know the value is negative, -n works too. Without the knowledge, -n would turn a positive number negative, which is what this lesson's function does on purpose.

    How do I check whether a number is negative?

    Compare it with zero: n < 0 is true only for negative numbers. Zero gives false, and so does NaN, because every comparison with NaN is false. Math.sign(n) is another option: it returns -1, 0, -0, 1 or NaN.

    How do I make a number negative?

    Put a minus sign in front of it, as in -n. To make sure the result is never positive, use -Math.abs(n).

    Edge cases and common mistakes

    • Always returning -n. This fails the already-negative case: negative(-4) would return 4.
    • Using n <= 0 versus n < 0. Both are valid. They differ only for zero: the version with <= returns 0, while the one with < returns -0.
    • Forgetting the return. Writing -n; on its own line computes a value and throws it away, and the method returns undefined.
    • Decimals. negative(2.5) returns -2.5 and negative(-2.5) returns -2.5. The code never assumes whole numbers.
    • Strings. A numeric string such as "7" is converted to a number by -n, so negative("7") returns the number -7. The method expects a number, so it is better to convert the input yourself first.

    Key takeaways

    • Check the sign before flipping it, because the unary minus makes negative numbers positive.
    • if (n < 0) return n; else return -n; solves the lesson. -Math.abs(n) does the same job in one expression.
    • Negating 0 gives -0, which equals 0 under === but prints differently in the console.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free