@@ -19,14 +19,39 @@ Use console.log() to clearly show the before-and-after type conversions.
19
19
*/
20
20
21
21
22
+ // Part 1: Debugging Challenge
22
23
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
24
25
25
- let isValid = Boolean ( "false" ) ;
26
+ let isValid = ( "false" === "false" ) ; // Explicit comparison, now correctly reflects the intended result
26
27
if ( isValid ) {
27
28
console . log ( "This is valid!" ) ;
28
29
}
29
30
30
31
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