Skip to content

Commit 6d542ea

Browse files
committed
Add Check If A Number Is Positive Or Negative as a JavaScript til
1 parent 2911e35 commit 6d542ea

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1169 TILs and counting..._
13+
_1170 TILs and counting..._
1414

1515
---
1616

@@ -364,6 +364,7 @@ _1169 TILs and counting..._
364364
- [Basic Date Formatting Without A Library](javascript/basic-date-formatting-without-a-library.md)
365365
- [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md)
366366
- [Check Classes On A DOM Element](javascript/check-classes-on-a-dom-element.md)
367+
- [Check If A Number Is Positive Or Negative](javascript/check-if-a-number-is-positive-or-negative.md)
367368
- [Check If Something Is An Array](javascript/check-if-something-is-an-array.md)
368369
- [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md)
369370
- [Compare The Equality Of Two Date Objects](javascript/compare-the-equality-of-two-date-objects.md)
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Check If A Number Is Positive Or Negative
2+
3+
The
4+
[`Math`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math)
5+
module has a handy function for checking if a number is _positive_ or
6+
_negative_. Or _zero_, for that matter.
7+
8+
It is
9+
[`Math.sign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign).
10+
11+
```javascript
12+
> Math.sign(5)
13+
1
14+
15+
> Math.sign(-5)
16+
-1
17+
18+
> Math.sign(0)
19+
0
20+
```
21+
22+
Any positive number will result in `1`. Any negative number will result in
23+
`-1`. If the number happens to be `0`, then `0` will be returned.
24+
25+
This function goes real well with a switch statement.
26+
27+
Note also that anything that isn't a number will result in `NaN`.
28+
29+
```javascript
30+
> Math.sign("one")
31+
NaN
32+
```

0 commit comments

Comments
 (0)