JS Datatype Conversions

Download (.odt) Download (Markdown)

String to number

[hook]

Using parseInt(string, radix) function (radix parameter is optional, 10 if not provided):

Using parseFloat(string) function:

Using constructor of Number object:

Using unary + operator:

Number to string

[hook]

Using toString() method:

String to boolean

[hook]

"true" to true and "false" to false

Using === (identity) operator:

(parentheses are optional but improve readability)

Using test(string) method on a case sensitive regex:

Using test(string) method on a case insensitive regex:

Truthy values to true and falsy values to false

Truthy values: any string that isn't empty (contains at least one character)

Falsy value: empty string

Using constructor of Boolean object:

Using double NOT operator (to invert result of single NOT operator):

Boolean to string

[hook]

Using toString() method:

Number to boolean

[hook]

Truthy values: each integer and float number except for 0

Falsy value: 0

Using constructor of Boolean object:

Using double NOT operator (to invert result of single NOT operator):

Boolean to number

[hook]

Using ternary operator (recommended - fastest benchmark):

More about ternary operator

Using unary + operator:

Using constructor of Number operator: