Skip to content

Commit 080bc17

Browse files
committed
Completed assignment tasks and modifications to code
1 parent ce92942 commit 080bc17

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

explicit-and-implicit-conversion-in-javascript.js

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,40 @@ Use console.log() to clearly show the before-and-after type conversions.
1818
1919
*/
2020

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+
*/
2225
let result = "5" - 2;
2326
console.log("The result is: " + result);
2427

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+
*/
2532
let isValid = Boolean("false");
2633
if (isValid) {
2734
console.log("This is valid!");
2835
}
2936

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+
*/
3041
let age = "25";
31-
let totalAge = age + 5;
42+
let totalAge = Number(age) + 5;
3243
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

Comments
 (0)