r/learnjavascript • u/[deleted] • Jul 11 '20
My function says that -4 is positive when it should be negative. Why?
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
letbut unless you plan to modify your function further down your code, you should useconstinsteadin real life, you wouldn't write
Arrowin the name of a functionyour 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
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 thatisNaN("")returnsfalse.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 returnsNaNif 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 thatNumber.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
isPositivepart 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 withisorhasshould be reserved for functions you expect to return a boolean (trueorfalse).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
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
functionkeyword here? Unless you're dealing withthis, I feel like old school, normal function syntax would be more readable in this case.function isPositive (num) {...}1
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,
thisrefers 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 andthisoften (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
Jul 11 '20
[deleted]
1
u/yadoya Jul 11 '20
the problem is
isNaN(null) == falseandisNaN("") == falseSo
isNaN(parseInt(number))seems the best way to do it2
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
2
2
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
5
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.
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.