🎄 Join our Annual Holiday wargame and win prizes!


Dangerous casting of Number type in JavaScript/TypeScript

17/11/2021

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

Deco line
Deco line

Play AppSec WarGames

Want to skill-up in secure coding and AppSec? Try SecDim Wargames to learn how to find, hack and fix security vulnerabilities inspired by real-world incidents.

Deco line
Deco line

Got a comment?

Join our secure coding and AppSec community. A discussion board to share and discuss all aspects of secure programming, AppSec, DevSecOps, fuzzing, cloudsec, AIsec code review, and more.

Read more