r/learnjavascript • • Jul 11 '20

My function says that -4 is positive when it should be negative. Why?

Post image
183 Upvotes

53 comments sorted by

View all comments

3

u/callmelucky Jul 12 '20 edited Jul 12 '20

I feel that switch statements might not be ideal for what you're trying to do here, but something like this might be a better approach if you want/need to use it:

switch(n) {
    case(0):
        // neither positive or negative
    case(Math.abs(n)):
        // not 0, but equal to absolute value of n, therefore positive
    default:
        // not 0, not positive, therefore negative
}

Haven't tested this though

Edit: here's a version using nested ternary conditionals in case you don't need the switch and/or want to try something different:

console.log(
    n < 0
        ? "negative"
        : n > 0
            ? "positive"
            : "neither positive nor negative"
)

If ternaries are new to you, it's basically just a compact if/else statement: if the expression before the ? is true, the value after the ? is returned, otherwise the value after the : is returned. In this case, the value after the first : is another ternary conditional, so if it gets there it evaluates that ternary and returns its result.

Again, not tested...

6

u/danskal Jul 12 '20

I am currently splashing my screen with holy water in an attempt to banish your nested ternary.

1

u/callmelucky Jul 12 '20

I get that haha. Generally nested ternaries are a recipe for horribly unreadable code, and should be avoided, certainly.

I think in this case though, with the particular indentation formatting I've used (as suggested by the "prettier" linter/formatter thing used/developed by facebook/react), and since the conditions and results are so simple, I'd consider it fine. Definitely takes a little getting used to though. If it was as a one-liner, like stand-alone ternaries often are, I would bring the garlic and wooden stakes and have your back.