๐Ÿš€ Submit a Challenge โ€” SecDim AppSec Village CTF at DEF CON 34 and Win a ROG Xbox Ally

Dangerous casting of Number type in JavaScript/TypeScript

Blog1 min read

In our first Defensive Programming principle we learnt that if we are dealing with weakly typed languages, we must first make sure it has the expected type before safety checks.

In JavaScript/TypeScript we should be careful to use a safe method to perform type casting as commonly used parserInt() or parseFloat() method may have unsafe results. Why? this is the excerpt from cheatsheet of Numeric Overflow lab (see the patch branch)

Use `Number(value)` for explicit coercion to Number type.

`parseInt()` or `parseFloat()` should not be used as substitute for coercion.
Unlike parsers, `Number(value)` is stricter and more safe for coercion:

* false becomes 0, true becomes 1
* null becomes 0, undefined becomes NaN
* If a string looks like a number, it becomes that number. 
* The empty string '' becomes 0. 
* Other strings become NaN.

TIP: Unary `+` operator is equivalent to `Number(value)`

Give it a try: Learn - SecDim

Questions or comments? Discuss this post on SecDim Community โ†’

Try it yourself

Find, Hack and Fix Your First Vulnerability

Reading about security bugs is one thing โ€” fixing one is how the skill sticks. Play a free challenge from the wargame, no setup required.