The javascript code looks like a "sieve"

I sincerely prefer this coding style. You just sieve out invalid
inputs, then do the code assuming it is valid.

We avoid nested if loops, and it is easier to put a new condition
check on the input.