File tree Expand file tree Collapse file tree 1 file changed +22
-4
lines changed Expand file tree Collapse file tree 1 file changed +22
-4
lines changed Original file line number Diff line number Diff line change @@ -19,14 +19,32 @@ Use console.log() to clearly show the before-and-after type conversions.
19
19
*/
20
20
21
21
22
- let result = "5" - 2 ;
22
+ let result = Number ( "5" ) - 2 ; // Use explicit Number() conversion
23
23
console . log ( "The result is: " + result ) ;
24
24
25
- let isValid = Boolean ( "false" ) ;
25
+ let isValid = Boolean ( "false" ) === true ; // Or use a specific condition
26
26
if ( isValid ) {
27
27
console . log ( "This is valid!" ) ;
28
28
}
29
29
30
30
let age = "25" ;
31
- let totalAge = age + 5 ;
32
- console . log ( "Total Age: " + totalAge ) ;
31
+ let totalAge = Number ( age ) + 5 ; // Convert age to a number
32
+ console . log ( "Total Age: " + totalAge ) ; // Now it's 30
33
+
34
+ // Examples
35
+ // Implicit Type Conversion (String + Number)
36
+ let implicitConversion = "5" + 2 ; // JavaScript implicitly converts 2 to a string and concatenates
37
+ console . log ( "Implicit Conversion Result: " + implicitConversion ) ; // Output: "52" (String)
38
+
39
+ // Explicit Type Conversion (String to Number)
40
+ let explicitConversion = Number ( "5" ) + 2 ; // Explicitly convert the string "5" to a number before addition
41
+ console . log ( "Explicit Conversion Result: " + explicitConversion ) ; // Output: 7 (Number)
42
+
43
+
44
+ // Handling Edge Case: NaN and undefined
45
+ let invalidConversion = Number ( "hello" ) ; // "hello" is not a number, so the result is NaN
46
+ let undefinedConversion = Number ( undefined ) ; // undefined is converted to NaN
47
+
48
+ console . log ( "Invalid Conversion Result (NaN): " + invalidConversion ) ; // Output: NaN
49
+ console . log ( "Undefined Conversion Result (NaN): " + undefinedConversion ) ; // Output: NaN
50
+
You can’t perform that action at this time.
0 commit comments