Skip to content

Commit 2129258

Browse files
committed
complete the tasks: type conversion
1 parent ce92942 commit 2129258

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

explicit-and-implicit-conversion-in-javascript.js

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,30 @@ Use console.log() to clearly show the before-and-after type conversions.
1818
1919
*/
2020

21-
22-
let result = "5" - 2;
21+
// JavaScript converts "5" into a number so the result is correct. But better to convert it explicitely for clarity:
22+
let result = Number("5") - 2;
2323
console.log("The result is: " + result);
2424

25-
let isValid = Boolean("false");
26-
if (isValid) {
25+
let isValid = "false"; // Boolean() converts the string "false" into true because it is not empty
26+
// fix: remove Boolean(), compare to the string "true" instead
27+
if (isValid === "true") {
2728
console.log("This is valid!");
2829
}
2930

3031
let age = "25";
31-
let totalAge = age + 5;
32+
let totalAge = Number(age) + 5; // JavaScript converts 5 into a string and concatinates two strings.
33+
// Fix: use Number() to convert age into a number.
3234
console.log("Total Age: " + totalAge);
35+
36+
// - One example of implicit type conversion.
37+
let implicitStrToNum = "2" * 2; // string "2" is converted into a number
38+
console.log(implicitStrToNum); // Output: 4
39+
40+
console.log("Hi" * 5); // Output: NaN. "Hi" cannot be converted into a number
41+
console.log(null + 5); // Output: 5. Null is converted into 0
42+
43+
// - One example of explicit type conversion.
44+
let explicitNullToBool = Boolean(null);
45+
console.log(explicitNullToBool); // Output: false
46+
// explicit null to string:
47+
console.log(String(null) + "Hi"); // Output: "nullHi". null is converted into a string "null"

0 commit comments

Comments
 (0)