Skip to content

Mathematical Javascript Tricks

Paul "Joey" Clark edited this page Nov 23, 2018 · 6 revisions

Conditional numbers

Thanks to Javascript type coercion, if you need a 0 you can often get away with false instead.

k=i>4?2*i:0   // BEFORE
k=i>4&&2*i    // AFTER

If we want a 1 then we can use the same trick but with || and inversed logic

k=i<5?1:2*i   // BEFORE
k=i<5||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

Logic

Comparing two numbers requires ==. Or does it?

Whilst 0 is falsey in Javascript, 1, 2, -1 and -2 are all truthy.

i==25&&drawSilver()
i-25||drawSilver()

Mathematics

Square followed by square-root is the same as Math.abs()

x=Math.abs(p)   // BEFORE
x=(p**2)**.5    // AFTER
x=((p**2)**.5)  // DISASTER

As you can see above, this is not always a saving. If you need to use that expression inline, and find you must place brackets around the expression, then Math.abs(...) will be shorter!