File tree Expand file tree Collapse file tree 1 file changed +20
-5
lines changed Expand file tree Collapse file tree 1 file changed +20
-5
lines changed Original file line number Diff line number Diff line change @@ -18,15 +18,30 @@ Use console.log() to clearly show the before-and-after type conversions.
18
18
19
19
*/
20
20
21
-
22
- let result = "5" - 2 ;
21
+ // JavaScript converts "5" into a number so the result is correct. But better to convert it explicitely for clarity:
22
+ let result = Number ( "5" ) - 2 ;
23
23
console . log ( "The result is: " + result ) ;
24
24
25
- let isValid = Boolean ( "false" ) ;
26
- if ( isValid ) {
25
+ let isValid = "false" ; // Boolean() converts the string "false" into true because it is not empty
26
+ // fix: remove Boolean(), compare to the string "true" instead
27
+ if ( isValid === "true" ) {
27
28
console . log ( "This is valid!" ) ;
28
29
}
29
30
30
31
let age = "25" ;
31
- let totalAge = age + 5 ;
32
+ let totalAge = Number ( age ) + 5 ; // JavaScript converts 5 into a string and concatinates two strings.
33
+ // Fix: use Number() to convert age into a number.
32
34
console . log ( "Total Age: " + totalAge ) ;
35
+
36
+ // - One example of implicit type conversion.
37
+ let implicitStrToNum = "2" * 2 ; // string "2" is converted into a number
38
+ console . log ( implicitStrToNum ) ; // Output: 4
39
+
40
+ console . log ( "Hi" * 5 ) ; // Output: NaN. "Hi" cannot be converted into a number
41
+ console . log ( null + 5 ) ; // Output: 5. Null is converted into 0
42
+
43
+ // - One example of explicit type conversion.
44
+ let explicitNullToBool = Boolean ( null ) ;
45
+ console . log ( explicitNullToBool ) ; // Output: false
46
+ // explicit null to string:
47
+ console . log ( String ( null ) + "Hi" ) ; // Output: "nullHi". null is converted into a string "null"
You can’t perform that action at this time.
0 commit comments