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

164

u/tomoe_mami_69 Jul 11 '20 edited Jul 11 '20

Switch case is not the same as if. It’s evaluating whether -4 === (-4 < 0), which is false.

Edit:

similar switch statement, but entering into the first statement. I hope this demonstrates how switch statements are executed.

Also the Mozilla documentation is excellent for gaining an understanding of exactly how Javascript actually works.

23

u/[deleted] Jul 11 '20

You're an absolute genius! Thank you so much.

13

u/intertubeluber Jul 11 '20

You just introduced pattern matching to JavaScript. You're the genius!

0

u/[deleted] Jul 11 '20

[deleted]

17

u/intertubeluber Jul 11 '20

No offense, but yikes.

0

u/[deleted] Jul 11 '20

[deleted]

14

u/intertubeluber Jul 11 '20

Because the switch statement is meant to evaluate an expression. Evaluating a constant value, like true, adds code without meaning.

What's the benefit of that pattern over an if/else statement?

0

u/[deleted] Jul 11 '20

[deleted]

3

u/NotSoLeetCode Jul 11 '20

You could just add enters to your if code and it would be very similar in conciseness to the switch code.

if (
	(isLoading && state === 'something') ||
	(! isLoading && state === 'something-else') ||
	state === 'some-third-option' ||
	someOtherVariable ||
	state === 'something'
) {
	doTheThing();
else {
	
}

0

u/[deleted] Jul 11 '20

[deleted]

→ More replies (0)

1

u/intertubeluber Jul 11 '20

The if statement should be refactored, but that switch statement (IMO) is not better. There's so much noise with the breaks and useless switch(true). I'd just pull each case out into a variable to improve readability. Some of the other cases (like in the article you linked), I'd define an object map with key being the case and value being the result ( or function that provides the result).

If I really wanted to use pattern matching in a language that didn't support it, I'd consider a third party library.

Having said that, if it's a small team and everyone agrees on that pattern, I wouldn't bike shed.

1

u/bmw2621 Jul 12 '20

I don't know about JS, but in Java a switch is evaluated all at once and is more performant than if...else which evaluates each condition sequentially. If I remember correctly (in Java) 5 or more conditions should use a switch.

0

u/i-can-sleep-for-days Jul 11 '20

I think the question the person you are replying to is asking is that JS's switch syntax seems hacky and unconventional to other languages that have switch statements.

Usually, you switch on a variable to match if it is one of the cases that you have defined.

3

u/StoneCypher Jul 12 '20

JS's switch syntax seems hacky and unconventional to other languages that have switch statements.

this is how almost all languages' switch statements work though

.

Usually, you switch on a variable to match if it is one of the cases that you have defined.

you might imagine that, but then you try this in c, and ...

similarly, people might think that 4[yourArray] is nonsense, but, it isn't

0

u/StoneCypher Jul 12 '20

i do not find that concise (or maintainable)

let current;

if      ( isLoading && state) { current = 'something'; }
else if (!isLoading && state) { current = 'something-else'; }

let shouldEngage = ((current === 'something') || (state === 'some-third-option'));

if (someOtherVariable || shouldEngage) { doTheThing(); }

2

u/thatguyonthevicinity Jul 11 '20

wow this is new to me, thanks so much!

4

u/[deleted] Jul 11 '20

Actually the documentation refers to the part after case but before the ”:” as an expression. Documentation says “An expression is any valid unit of code that resolves to a value.” So it can be used as an if statement. OP is just missing parentheses.

“Case (number < 0):” will do what he wants it to do.

2

u/tomoe_mami_69 Jul 11 '20

1

u/[deleted] Jul 11 '20 edited Jul 11 '20

I apologize, the switch statement is still doing a comparison (with the ===), so its ultimately going to be boolean value. So you need to check for that

let expression = -4;

switch(true){

case (expression < 0):console.log(`${expression} is a negative number`);break

case (expression === 0):console.log(`${expression} is zero`);break}

Screenshot

edit: fixed code.

3

u/callmelucky Jul 12 '20

What I'm getting from this is that switch statements probably aren't really suitable for what OP is trying to do...

3

u/[deleted] Jul 12 '20

They are horrible for what OP’s doing

They are super slow

1

u/callmelucky Jul 12 '20

Holy shit. I never really liked switch statements. They don't exist in Python, my "native tongue" (though I hear there is a push to add them...), and I always found them hideously verbose and weird. Good to know there is a performance-oriented reason to avoid them lol (not that performance is likely of much concern for OP's use case though).

That said, I came up with a switch approach which I thought was pretty neat, at least syntactically. I prefer the nested ternary though of course :)

1

u/[deleted] Jul 12 '20

This Youtuber says that if else statements aren't ideal. If you don't want to watch entire video you can get straight to his rant on if else starting at 2:05. Whether switch statements are better or worse seems to be quite the a controversial subject, haha. I'm not trying to prove anything here. Simply thought it was funny.

1

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

This Youtuber says that if else statements aren't ideal.

Well to be fair, from what I saw that video is not saying that at all, it's saying that evaluating a bunch of if statements that don't need to be evaluated is not ideal. This is just generally true: doing things that don't need to be done is not ideal. Nesting conditions in conditions in conditions is also "bad" as the video suggests, because it makes code less readable and more "brittle" (susceptible to bugs and difficult to change).

As for switch vs if/else-if/else constructs, if you're concerned about performance (tip: you probably shouldn't be), it looks like, in JavaScript at least, switch statements are a bad choice.

In practice though for the most part, if the semantics (what the code means and does) are the same, the choice of syntax should really about what you (or your team or boss etc) prefers. That is, it's a matter of opinion. As I said, I generally lean away from switch statements for no good reason beyond "I haven't used them much and I don't like the way they look". The main reason I suggested that a switch statement might not be the best choice for your function is that it seems a little trickier to make the syntax represent the semantics clearly than it would be if you used if/else control flow or ternary conditionals.

To that point, I made a comment elsewhere here with a switch statement solution that I thought was pretty neat, but I don't think that (without code comments at least*) it conveys the semantics as well as an if/else or ternary based solution would. In that case the switch statement is the "worse" choice. In many other cases, the switch would be "better" - more readable and more semantically transparent.

*re code comments: generally, relying on comments to explain what your code does is considered a "code smell". If you can make your code more "readable" through careful choice of variable/function names, formatting, choice of syntax for a statement (eg if/else vs switch vs ternary) etc, then that's a better way to go. The general guideline is that comments should explain why you do something, not what you do, and even then, only when necessary.

Ok sorry for the rambling, I did note that you weren't trying to prove anything, I just got carried away explaining stuff. Partly for my own benefit - explaining things to others can be very helpful to one's own understanding :) I have heard references to the atrocities of YandereDev, and that video does look pretty entertaining, I'll be sure to check out the rest of it :)

1

u/jonnysake Jul 12 '20

This. To put it in plain terms, you can't have a conditional in a `case`, only the top-level `switch` invocation.

36

u/yadoya Jul 11 '20 edited Jul 11 '20

A few things.

  • someone already answered, but I'd like to add this is a very poor way of comparing values. Switch cases are pretty long to write and debug, so I suggest you avoid them as much as possible.

  • you used let but unless you plan to modify your function further down your code, you should use const instead

  • in real life, you wouldn't write Arrow in the name of a function

  • your function doesn't handle the case when your argument is not a number. In your case isPositiveArrow("hello") behaves as if "hello" is a positive number.

  • In real life, you must prepare for lots of different strange things to get passed to your functions as arguments, for example null, true, false, undefined, "hello", {}, function(){console.log('hi')}, [1, 2, 3], String, [], [,,,], [null] or simply an empty string "". So you need to handle errors.

A better way to write your function would be:

const isPositive = number => {
    if (isNaN(parseInt(number))) { throw new Error("Argument is not a number")}   
    return number > 0;
}

EDIT: this article seems to suggest that you should use Number.isNan() rather than isNaN()

12

u/[deleted] Jul 11 '20

const isPositive = number => { if (isNaN(parseInt(number))) { throw new Error("Argument is not a number")} return number > 0; }

I'll be honest. All of this looks like an alien language to me at the moment, but I will definitely attempt to break it down to decipher what it all means and how it works, haha. Thank you for the constructive feedback.

11

u/yadoya Jul 11 '20

no worries! Actually, I didn't know how to do this a few minutes ago either. I wanted to make sure that the argument was a number, so I first did if (number != null) and realized it didn't work with "hello"

So I googled a bit and found isNaN(). I started using it but then I realized that isNaN("") returns false.

So I googled a bit more and found that the best way to check if something was a number was to use parseInt() and the good thing about it is that it indeed returns NaN if you pass it "hello"

So I just put these together and wrote isNaN(parseInt(number)). I tested it with lots of different arguments and it seems to do the trick. That was until I realized that Number.isNaN() is actually better, because weirdly enough, isNaN('string') returns false. Strange, huh?

So mainly I just used lots of google lol

8

u/DWIGHT_CHROOT Jul 12 '20

/u/CallMeZeta I hope you pay the most attention to this comment. You're going to do this a tonnn. Google something, test it out, Google some more, and eventually it should lead to something that works or doesn't work but either way you will have learned something.

3

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

There's lots of useful info there, but it should be noted that it doesn't do what you were trying to do. In particular it doesn't detect 0 at all, and it returns a value (a boolean) rather than printing out its result.

In defence of the parent commenter though:

The name of your function (that is, the isPositive part at least) implies that the function should do what the parent commenter's function does! So either the function is named poorly, or your attempt at the solution was not appropriate in the first place, whether it worked or not.

To take an important tangent from that observation: possibly the very best thing you can do as a beginner is to get into the habit of naming things well. I cannot overstate how important this is. A name should clearly and accurately represent the semantic ("meaningful") value or purpose of the variable or function. Bad names will make debugging and expanding your code massively more difficult and time consuming. An extra few seconds of thought and an extra few characters to type are so, so worth the time and headaches you will save as you continue work on the code. Furthermore, it is a way to immeasurably improve the quality of your code without requiring any "expertise" whatsoever! All it takes is a tiny bit of extra thought and common sense.

That said, for what you were attempting a better function name would be something like logPosOrNegOrNeither. This tells you that the purpose of the function is to log something, and it tells you (roughly) what you expect it to log. Names starting with is or has should be reserved for functions you expect to return a boolean (true or false).

The difference between what your function name implies and what you are attempting to do is the difference between asking someone "is -4 positive?", and commanding them "if -4 is positive, write (something) down, if it's negative write (something else) down, if it's neither write (something else again)". Obviously these are quite different things.

2

u/PixelatorOfTime Jul 12 '20

That’s okay, and the fact that you recognize it means you’re focusing on where you need to be (learning language constructs and how logic and variables work), rather than diving straight into the deep end.

What most people fail to realize when they explain programming stuff is that there’s an enormous amount of info that you know that you take for granted. In all these examples (while they’re not wrong and do show some best practices), some of that implicit knowledge is sneaking in as assumptions about what you’re actually doing—and maybe as a way to flex… (I kid)

You’re not writing enterprise software here, you’re just checking a number to try out some concepts. Don’t let yourself get bogged down by this more advanced stuff and try to learn things like that as they come. That will help you avoid putting some code in just because someone said to rather than because you know it needs to be there and what it’s doing. Just make cool stuff, and as long as you’re not dealing with actual users’ personal data, experiment until things work!

1

u/saito200 Jul 11 '20

You can ignore lines 2 to 4 and consider them as "advanced". You should easily get the logic of what remains

2

u/[deleted] Jul 12 '20

Most of your advices where good, but your last one deserves a rewording, at least, as it contradicts a little with your example. One doesn't make a function check for everything. Suppose a function with the signature invertArray(array). It's obvious that it expects an array right? The function should check if the passed array is in the set of valid arrays (arrays only with numbers, array only with strings, array with numbers and strings but no objects and etc...) and at a maximum check if what was passed is an array (as in your example). Whose fault it is if something else gets passed? The user who probably didn't read the documentation.

1

u/Arumai12 Jul 12 '20

I also disagree with that last point. Just because js is loosely typed doesnt mean every function has to handle every type. Through proper testing and making your code readable you can guarantee that the function will always be called with a number. If you can't guarantee it or its so far removed from the rest of the code that it's easy to pass in the wrong type of data then you should provide explicit behavior for non numbers.

0

u/benabus Jul 11 '20

Is there a reason not to just use the function keyword here? Unless you're dealing with this, I feel like old school, normal function syntax would be more readable in this case.

function isPositive (num) {...} 

1

u/[deleted] Jul 12 '20

If you don't mind me asking. Why is 'this' useful in an arrow function and not an if function? What would the difference be? Does 'this' only work in arrow functions?

2

u/PixelatorOfTime Jul 12 '20

In traditional functions, this refers to the context of what you’re doing; maybe an event or sometimes even the function itself. Arrow functions don’t work the same way and this often (but not always) refers to the greater context of where the arrow is defined, perhaps the window/document, or maybe a parent function.

While it’s 100% an important thing to learn about, wait a little bit before trying to grok it.

2

u/thatguyonthevicinity Jul 11 '20

I think that's just personal preference, I prefer to use arrow function whenever possible. Well at the very least, use the team convention, and both work just as fine, especially if, as you said, no one's dealing with this.

1

u/yadoya Jul 11 '20

yeah I guess you're right. I never know when to use arrow vs normal function syntax, but OP seemed to want to use an arrow function.

Why would you prefer a normal syntax?

1

u/benabus Jul 11 '20

I just find it more readable. I tend to prefer verbosity.

I use normal syntax for stand-alone functions and usually limit arrow functions to callbacks or when I really need to manage the scope of this.

In practice, you almost never use stand alone functions, though, so it's probably a moot point. Most functions tend to be used as methods on an object, in which case, you'd probably want to use the method definition shorthand.

But, of course, there's always the case that there are other technical reasons to use one versus the other that I'm unaware of.

1

u/mw9676 Jul 12 '20

I mean React is one of the most popular JS frameworks and has been moving consistently away from class based components, as has the language in general (es6 and up). I don't think your assessment that one never uses standalone functions is accurate. Also, I would argue using arrow functions is vastly more readable, especially as you start to compose them or even just write in a more functional way and pass them around as first class objects. That said I prefer verbosity too, but not verbose boiler plate (ie explicit naming but not explicitly writing "function")

0

u/[deleted] Jul 11 '20

[deleted]

1

u/yadoya Jul 11 '20

the problem is isNaN(null) == false and isNaN("") == false

So isNaN(parseInt(number)) seems the best way to do it

2

u/Derpcock Jul 11 '20

If you're not dealing with infinite numbers, isFinite is a quick way to validate a number too. It also handles typecasting string numbers to numbers iirc.

4

u/kevozo212 Jul 12 '20

Why use switch over if here?

Just do if less than 0, negative. If greater than 0 positive. If 0, none.

2

u/adlhitrofel Jul 12 '20

Yep why swich case if statement will be more usefull

2

u/UmutReel Jul 12 '20

What is your theme?

2

u/bobbywjamc Jul 12 '20

Instead of default use case number > 0

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.

1

u/unswornkoshur Jul 12 '20

Which color scheme are you using?

5

u/[deleted] Jul 11 '20

[removed] — view removed comment

-14

u/boringuser1 Jul 11 '20

Using const is *usually* not justified.

7

u/thatguyonthevicinity Jul 11 '20

should that be the other way around?

const probably should be the default, since we don't want to *accidentally* change values. Let should be used when we know we want to change a variable's value.

wdyt?

-9

u/boringuser1 Jul 11 '20

Const makes the binding immutable and not the value and doesn't help the compiler. Honestly 9 times out of 10, just why.