Casting

Contents

Casting#

The conversion surface across the eight types, plus the == / === contrast.

From / to

How

any to string

String(x) or ` `${x}` ` (calls .toString()); JSON.stringify(x) for objects.

string to number

Number(s) (strict; ""0, "x"NaN).

string to integer

parseInt(s, 10); always pass the radix.

string to float

parseFloat(s); lenient, reads the leading float.

any to boolean

Boolean(x) or !!x.

number to bigint

BigInt(n); n must be an integer.

bigint to number

Number(big); precision may be lost.

== triggers implicit coercion (1 == "1" is true); === does not (1 === "1" is false). The operator writes === and !== by default.

Strict equality compares by type and value.

1 === "1";            // false

Loose equality coerces before comparing.

1 == "1";             // true

== null is the one common, defensible loose form; it matches both null and undefined in one comparison.

x == null;            // true for both null and undefined

References#

  • number for parseInt / parseFloat details.

  • boolean for the falsy list.

  • Operators for the equality operators in context.