@@ -19,14 +19,39 @@ Use console.log() to clearly show the before-and-after type conversions.
19
19
*/
20
20
21
21
22
+ // Works due to implicit conversion
22
23
let result = "5" - 2 ;
23
- console . log ( "The result is: " + result ) ;
24
+ console . log ( "The result is: " + result ) ;
24
25
26
+ // "false" (as a non-empty string) is truthy, so this block will run
25
27
let isValid = Boolean ( "false" ) ;
26
28
if ( isValid ) {
27
29
console . log ( "This is valid!" ) ;
28
30
}
31
+ // Fix not needed here.
29
32
33
+
34
+ // This line causes a bug because it performs string concatenation, not addition
30
35
let age = "25" ;
31
- let totalAge = age + 5 ;
32
- console . log ( "Total Age: " + totalAge ) ;
36
+ let totalAge = Number ( age ) + 5 ;
37
+ console . log ( "Total Age: " + totalAge ) ;
38
+
39
+ // Used Number() to explicitly convert age from a string to a number
40
+
41
+ // Implicit Type Conversion Example
42
+ let implicitConversion = "10" * 2 ;
43
+ console . log ( "Implicit result:" , implicitConversion ) ;
44
+ console . log ( "Type of result:" , typeof implicitConversion ) ;
45
+
46
+ // The * operator triggers implicit conversion from string to number
47
+
48
+ // Explicit Type Conversion Example with Edge Case
49
+ let edgeCase = undefined ;
50
+ let convertedValue = Number ( edgeCase ) ;
51
+ console . log ( "Converted value:" , convertedValue ) ;
52
+ console . log ( "Type of converted value:" , typeof convertedValue ) ;
53
+
54
+ // undefined cannot be directly converted to a valid number
55
+
56
+
57
+
0 commit comments