@@ -18,15 +18,40 @@ Use console.log() to clearly show the before-and-after type conversions.
18
18
19
19
*/
20
20
21
-
21
+ /* "5" here in the first chunk of code is a string, however implicit type conversion because
22
+ of the subtraction operator coerces it into a number, preserving the logic of the
23
+ code when it produces a result of 3. No error.
24
+ */
22
25
let result = "5" - 2 ;
23
26
console . log ( "The result is: " + result ) ;
24
27
28
+ /* Perhaps there is a logic error here? In that even though the boolean is false, isValid is true
29
+ and so "This is valid" prints. Perhaps you should inset a not operator, !, then? Otherwise I cannot
30
+ see what is wrong with this code which runs just fine.
31
+ */
25
32
let isValid = Boolean ( "false" ) ;
26
33
if ( isValid ) {
27
34
console . log ( "This is valid!" ) ;
28
35
}
29
36
37
+ /* In this final bit of code, because of the + operator the age vareiable as a string coerces the
38
+ number 5 into being a string as well, leading to the unexpected result of 255, an unlikely age.
39
+ By forcing age to a number with the Number() function, the code functions as expected, producing 30.
40
+ */
30
41
let age = "25" ;
31
- let totalAge = age + 5 ;
42
+ let totalAge = Number ( age ) + 5 ;
32
43
console . log ( "Total Age: " + totalAge ) ;
44
+
45
+ //Task 2
46
+
47
+ /* The Number() fucntion explicitly converts the ageInYears string to a number before 1 is added.
48
+ */
49
+ let ageInYears = "31" ;
50
+ let ageAtBirthday = Number ( ageInYears ) + 1 ;
51
+ console . log ( "Age on birthday is " + ageAtBirthday ) ;
52
+
53
+ /* The division operator implicitly coerces the string to a number.
54
+ */
55
+ let humanAge = "70"
56
+ let ageInDogYears = humanAge / 7
57
+ console . log ( "I am 70 years old, so my age in dog years is " + ageInDogYears + "." ) ;
0 commit comments