Skip to content

Commit a580b47

Browse files
committed
updated
1 parent ce92942 commit a580b47

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

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

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,39 @@ Use console.log() to clearly show the before-and-after type conversions.
1919
*/
2020

2121

22+
// Part 1: Debugging Challenge
2223
let result = "5" - 2;
23-
console.log("The result is: " + result);
24+
console.log("The result is: " + result); // No fix needed, implicit conversion works here
2425

25-
let isValid = Boolean("false");
26+
let isValid = ("false" === "false"); // Explicit comparison, now correctly reflects the intended result
2627
if (isValid) {
2728
console.log("This is valid!");
2829
}
2930

3031
let age = "25";
31-
let totalAge = age + 5;
32-
console.log("Total Age: " + totalAge);
32+
let totalAge = Number(age) + 5; // Explicit type conversion from string to number
33+
console.log("Total Age: " + totalAge); // Correct output: Total Age: 30
34+
35+
36+
//Part 2: Own Examples
37+
let num1 = "10"; // string
38+
let num2 = 5; // number
39+
let resultImplicit = num1 * num2; // Implicit conversion: string '10' is converted to a number
40+
console.log("Implicit conversion result: " + resultImplicit); // Output: 50
41+
42+
43+
44+
let str = "123abc"; // string with letters
45+
let numberExplicit = Number(str); // Explicit conversion to number
46+
console.log("Before explicit conversion: " + str); // Output: "123abc"
47+
console.log("After explicit conversion: " + numberExplicit); // Output: NaN
48+
49+
50+
51+
//Edge Case: NaN (Not-a-Number)
52+
let edgeCaseString = "xyz"; // A string that can't be converted to a number
53+
let edgeCaseNumber = Number(edgeCaseString); // Explicit conversion
54+
console.log("Edge case result: " + edgeCaseNumber); // Output: NaN
55+
56+
let isValidNaN = isNaN(edgeCaseNumber); // Check if the result is NaN
57+
console.log("Is NaN: " + isValidNaN); // Output: true

0 commit comments

Comments
 (0)