Skip to content

Mathematical Javascript Tricks

Vivek edited this page Sep 1, 2020 · 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()   // BEFORE
i-25||drawSilver()    // AFTER

Mathematics

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

x=Math.abs(p)      // BEFORE
x=(p*p)**.5        // AFTER
x=((p*p)**.5)      // NO SAVING

As you can see above, this is not always a saving. If you need to use the x expression inline, you may need to place brackets around it, in which case the original Math.abs(...) would have worked equally well.

A place where squaring can make a great saving is when we want to compare the magnitude of a number, with no regard for its sign (negative/positive). We can simply square the compared value too.

// We want to check if d is between -8 and +8 (exclusive)
h=Math.abs(d)<8
h=d*d<64

Numerical conditionals

Sometimes you need to do something special only once in a long loop - for example

X==N&&fillRect(X,Y,K,K)

You can use the XOR operator to shorten this - think of XOR as "bitwise difference detector"

X^N||fillRect(X,Y,K,K)

X^N is 0 only when X is equal to N