Start learning free

LESSON 88 OF 348 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating abs() in TypeScript: if and else

Practice Read the full explanation

The abs() function returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.

Create your own function abs() that recreates this functionality.

Examples:

abs(-1.217197940) ➞ 1.21719794

abs(-544.0) ➞ 544

abs(250.3) ➞ 250.3

abs(0) ➞ 0

abs(-0.14) ➞ 0.14

Note:

Do not use the abs() function provided by TypeScript (it will defeat the purpose of the challenge)


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 - CHALLENGES

    Recreating Abs in TypeScript, explained

    Problem overview

    The method abs of the class Solution takes a number n and returns its absolute value, the distance of n from zero. Negative numbers become positive, and everything else stays the same. The built-in function for this, Math.abs, is off limits, because the point is to build it yourself.

    The examples show the idea: abs(-1.21719794) is 1.21719794, abs(-544) is 544, abs(250.3) is 250.3, abs(0) is 0 and abs(-0.14) is 0.14. The input can be a decimal, which is no problem: TypeScript has a single number type for integers and decimals alike.

    Approach

    There are only two kinds of input. A negative number has to change sign, and a number that is zero or positive is already its own absolute value. That is a decision between two outcomes, which is exactly what if and else are for.

    To flip the sign of a negative number, negate it. The unary minus in -n turns -5 into 5, because -(-5) is 5. No multiplication by -1 or other trick is needed.

    Step by step

    1. Test for a negative number. Write an if whose condition is n < 0. The body can stay empty for the moment.
    2. Return the negation. Inside the if, return -n; gives the positive value of a negative input.
    3. Handle everything else. In the else branch, return n unchanged. Zero lands here, and that is correct, since the absolute value of 0 is 0. Use the usual layout, } else { on one line after the closing brace of the if.

    The solution in TypeScript

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

    A few details are worth knowing:

    • The types. n: number and the return type : number are annotations for the compiler. They disappear in the JavaScript that tsc produces, so the function does not check its argument at run time.
    • Every path returns. The if returns and the else returns, so the method always produces a number. Because each branch ends in a return, the else could be dropped and the last return n; placed after the if. The lesson keeps the else because it states the two cases clearly.
    • A method of a class. The function is written inside class Solution, so it is called on an instance: new Solution().abs(-3) gives 3.

    Edge cases and common mistakes

    • Zero. 0 < 0 is false, so abs(0) returns 0. Using n <= 0 would also work for ordinary zero, since -0 and 0 are the same for most purposes, but it does needless work.
    • Negative zero. JavaScript numbers have a signed zero. If the input is -0, the test -0 < 0 is false, so the method returns -0 as it was. When printed with console.log it shows as -0, whereas Math.abs(-0) gives 0. For normal use the two compare equal under ===, so this rarely matters.
    • NaN. Any comparison with NaN is false, so abs(NaN) falls into the else branch and returns NaN. That is the sensible answer.
    • Only negating. Returning -n for every input is a classic bug: positives would become negative. The test is what protects them.
    • Wrong comparison. A condition such as n > 0 with return -n is backwards. Read the condition aloud: "if n is below zero, flip it".
    • A string argument. TypeScript rejects abs("5") at compile time. Because types are erased, if a string got through at run time, "5" < 0 would be false and the string would be returned untouched.

    Testing

    Try these calls in the editor above. They are the lesson's own examples, plus the boundary values:

    • abs(-544) should give 544.
    • abs(250.3) should give 250.3.
    • abs(0) should give 0.
    • abs(-0.14) should give 0.14.

    The method does a single comparison and a single return, so its time and space use are constant. The work does not grow with the size of the number.

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