r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

40

u/a_dev_has_no_name Mar 19 '19 edited Mar 20 '19

~~anyNumber

Very short Bitwise operation to do rounding similar to the equivalent of Math.floor() i.e ~~5.9 // 5

It's handy for code golf or for angering coworkers

Edit: I didn't quite literally mean it's exactly the same as Math.floor I should've clarified on that. Also, I'm not suggesting anyone use this in production code, like I said it's nice for code golf.

28

u/anakappa Mar 19 '19

This is why we can't have nice things.

10

u/a_dev_has_no_name Mar 19 '19

Wait until you see the other tricks ಠ‿ಠ

14

u/thisguyfightsyourmom Mar 19 '19

Are you the guy who wrote the code I’m maintaining?

I hate you if so

14

u/rcfox Mar 19 '19

It's not the equivalent of Math.floor(). Math.floor() rounds towards negative infinity while integer truncation rounds towards zero.

> -2.3|0
-2
> Math.floor(-2.3)
-3

9

u/eGust Mar 19 '19

Bitwise operators will convert Number which is 64-bit precision IEEE-754 to 32-bit signed integer. So you will lose precision if your number is over 2**32, and will get -ve value if your number is between 2**31 and 2**32. I think that's why Airbnb eslint rules forbidden bitwise operators.

1

u/fgutz Mar 19 '19

I agree with AirBnB, don't use them unless you're building something really different/special that might call for some fancy bitwise operations (like emulating a CPU in JS or something like that)

But also, when is your average CRUD app going to hit a number as high as 2**31? Maybe in high level finance or sites with above average traffic (like reddit)

1

u/FormerGameDev Mar 25 '19

airbnb rules forbid anything that isn't obvious what it does at first glance.

6

u/Skhmt Mar 19 '19

asm.js uses anyNumber|0 to do the same thing

2

u/a_dev_has_no_name Mar 19 '19

Yeah, there are a few ways to do it. I was using num >> 0 before but ~~n is more concise and makes a little more sense (imo) like doing a double negation !!

1

u/kybernetikos Mar 19 '19

Engines that support asmjs use |0 as a backwards compatible type annotation. It means "this value is a 32 bit integer". It is not the same as Math.floor, although with some values it will behave like it.

5

u/HideousNomo Mar 19 '19

I've been using num | 0 for this very thing

1

u/fgutz Mar 19 '19

so I understand what's going with this with integers, 23|0 will always return 23 because you're comparing 10111 with 00000 so it will always return 10111.

So I assume this just casts the float to an integer and does the comparison, effectively doing a pseudo math.floor.

Like /u/rcfox pointed out, it doesn't work for negative integers:

Math.floor(-21.12) === -22
// but 
-21.12|0 === -21

1

u/kybernetikos Mar 19 '19

This actually turns the number into a 32 bit integer. It is not the same as Math.floor. test it on some large numbers to see the dramatic difference.