diff --git a/explicit-and-implicit-conversion-in-javascript.js b/explicit-and-implicit-conversion-in-javascript.js index ede0ccd..fd6308a 100644 --- a/explicit-and-implicit-conversion-in-javascript.js +++ b/explicit-and-implicit-conversion-in-javascript.js @@ -18,15 +18,40 @@ Use console.log() to clearly show the before-and-after type conversions. */ - +/* "5" here in the first chunk of code is a string, however implicit type conversion because +of the subtraction operator coerces it into a number, preserving the logic of the +code when it produces a result of 3. No error. +*/ let result = "5" - 2; console.log("The result is: " + result); +/* Although the code runs just fine, there is a logic error: when coerced to boolean a string which +is not empty is true, so the string "false" actually ends up being true and so the conditionl prints +this is valid. To remedy this, add the not operator, !, to the function. +*/ let isValid = Boolean("false"); -if (isValid) { +if (!isValid) { console.log("This is valid!"); } +/* In this final bit of code, because of the + operator the age vareiable as a string coerces the +number 5 into being a string as well, leading to the unexpected result of 255, an unlikely age. +By forcing age to a number with the Number() function, the code functions as expected, producing 30. +*/ let age = "25"; -let totalAge = age + 5; +let totalAge = Number(age) + 5; console.log("Total Age: " + totalAge); + +//Task 2 + +/* The Number() fucntion explicitly converts the ageInYears string to a number before 1 is added. +*/ +let ageInYears = "31"; +let ageAtBirthday = Number(ageInYears) + 1; +console.log("Age on birthday is " + ageAtBirthday); + +/* The division operator implicitly coerces the string to a number. +*/ +let humanAge = "70" +let ageInDogYears = humanAge / 7 +console.log("I am 70 years old, so my age in dog years is " + ageInDogYears + "."); \ No newline at end of file