-
Notifications
You must be signed in to change notification settings - Fork 67
Mathematical Javascript Tricks
Paul "Joey" Clark edited this page Jun 23, 2018
·
6 revisions
Thanks to Javascript type coercion, if you need a 0
you can often get away with false
instead.
k=i<5?0:2*i // BEFORE
k=i>4&&2*i // AFTER
Doing the same trick with ||
is slightly different because true
acts like a 1
.
k=i<8?1:2*i // BEFORE
k=i<8||2*i // AFTER
Similarly, true
can act like a 1
for multiplication
k=50+(i>5?20:0) // BEFORE
k=50+(i>5)*20 // AFTER
Square followed by square-root is the same as Math.abs()
x=Math.abs(p) // BEFORE
x=(p**2)**.5 // AFTER
But this is not always a saving. If you were to use that expression inline, and find you need brackets around the expression, then Math.abs(...)
will be shorter!