Values, Types, and Expressions
Type Conversion
Convert between strings and numbers explicitly.
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.
Type Conversion
type_conversion.js
Replay: real traced execution (multi-file project)
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);
const text = "7";
const num = Number(text);
const back = String(num);
const doubled = num * 2;
console.log("num=" + num);
console.log("back=" + back);
console.log("doubled=" + doubled);
const text = "100";
const num = Number(text);
const back = String(num);
const doubled = num * 2;
console.log("num=" + num);
console.log("back=" + back);
console.log("doubled=" + doubled);
text ← 42, num ← 42, back ← 42, doubled ← 84
1const text→ 42 = "42"; //@text="7", "100"2const num→ 42 = Number(text42);3const back→ 42 = String(num42);4const doubled→ 84 = num→ 42 * 2;56console.log("num=" + num42);7console.log("back=" + back42);8console.log("doubled=" + doubled84);outputnum=42 back=42 doubled=84
text ← 7, num ← 7, back ← 7, doubled ← 14
1const text→ 7 = "7";2const num→ 7 = Number(text7);3const back→ 7 = String(num7);4const doubled→ 14 = num→ 7 * 2;56console.log("num=" + num7);7console.log("back=" + back7);8console.log("doubled=" + doubled14);outputnum=7 back=7 doubled=14
text ← 100, num ← 100, back ← 100, doubled ← 200
1const text→ 100 = "100";2const num→ 100 = Number(text100);3const back→ 100 = String(num100);4const doubled→ 200 = num→ 100 * 2;56console.log("num=" + num100);7console.log("back=" + back100);8console.log("doubled=" + doubled200);outputnum=100 back=100 doubled=200
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 |
Exercise: type_conversion.js
Reproduce doubled=84, then use the pinned text values 7 and 100 to predict each doubled value.