Convert between strings and numbers explicitly.

Type Conversion

type_conversion.js
const text = "42";
const num = Number(text);
const back = String(num);
const doubled = num * 2;

console.log("num=" + num);
console.log("back=" + back);
console.log("doubled=" + doubled);

Follow the Conversion

  1. text starts as "42".
  2. Number(text) gives num = 42.
  3. String(num) gives back = 42.
  4. doubled = num * 2 becomes 84.
  5. The program prints num=42, back=42, and doubled=84. | text | num | back | doubled | | --- | --- | --- | --- | | "7" | 7 | 7 | 14 | | "42" | 42 | 42 | 84 | | "100" | 100 | 100 | 200 |
type-conversion `Number(...)` turns a numeric string into a number and `String(...)` turns a number back into text, so values can be used in the right context.

Exercise: type_conversion.js

Reproduce doubled=84, then use the pinned text values 7 and 100 to predict each doubled value.