Values, Types, and Expressions
Type Conversion
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
textstarts as"42".Number(text)givesnum = 42.String(num)givesback = 42.doubled = num * 2becomes84.- The program prints
num=42,back=42, anddoubled=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.