Skip to content

Commit 6773717

Browse files
committed
Debugged part 1 of code and gave examples of type conversion for part 2 of code
1 parent ce92942 commit 6773717

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

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

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,38 @@ Include at least one edge case, like NaN, undefined, or null .
1717
Use console.log() to clearly show the before-and-after type conversions.
1818
1919
*/
20-
21-
22-
let result = "5" - 2;
23-
console.log("The result is: " + result);
24-
25-
let isValid = Boolean("false");
20+
//Part 1: Debugging Challenge
21+
// explicit type conversation Number() needs to be used
22+
console.log("This is Part 1!")
23+
let result = Number("5") - 2; //using the number() conversion explicitly converts 5 into a number before subtraction
24+
console.log("The result is: " + result); //output is 3
25+
26+
//Boolean conversion of non-empty string
27+
let isValid = Boolean("false" === "true");//explicitly comparing to avoid a "false" Truth value
2628
if (isValid) {
2729
console.log("This is valid!");
30+
} else {
31+
console.log ("This is not valid!"); // output is "This is not valid"
2832
}
2933

34+
//make sure variable age is treated as a number for the operation
3035
let age = "25";
31-
let totalAge = age + 5;
32-
console.log("Total Age: " + totalAge);
36+
let totalAge = Number(age) + 5; //using the number() conversion explicitly converts 25 into a number before addition
37+
console.log("Total Age: " + totalAge); //output is 30
38+
39+
40+
41+
//Part 2: Write Your Own Examples
42+
43+
console.log("This is Part 2!")
44+
let implicitEx = "19" - 20; //javascript automatically defines "19" as a number
45+
console.log(implicitEx); //output is "-1"
46+
console.log(typeof implicitEx + " is the output."); //output is "number"
47+
48+
let explicitEX = "19" + "20";
49+
console.log(explicitEX);
50+
console.log(typeof explicitEX + " is the output before."); //output is string
51+
52+
let convertedNum = Number(explicitEX); //convert string to number
53+
console.log(convertedNum); //output is 1920
54+
console.log(typeof convertedNum + " is the output after."); //output is number

0 commit comments

Comments
 (0)