Skip to content

Commit efc3ffe

Browse files
committed
debugged example snippets and added examples of both explicit and implicit conversion.
1 parent ce92942 commit efc3ffe

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

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

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,34 @@ Use console.log() to clearly show the before-and-after type conversions.
1919
*/
2020

2121

22-
let result = "5" - 2;
22+
let result = String("5" - 2);
2323
console.log("The result is: " + result);
24+
console.log(typeof result);
25+
//adding String() makes the result more predictable by not leaving the final type up for implicit conversion.
2426

25-
let isValid = Boolean("false");
27+
let isValid = Boolean("");
2628
if (isValid) {
2729
console.log("This is valid!");
2830
}
31+
console.log(isValid);
32+
//"false" as a string value inside the boolean function was returning a true value because any non-empty string value is considered truthy by JavaScript.
2933

30-
let age = "25";
34+
let age = Number("25");
3135
let totalAge = age + 5;
3236
console.log("Total Age: " + totalAge);
37+
//the totalAge variable was concatenating the 'age' variable with the number 5 which was producing 255. Adding the number() function meant the number is the correct data type for mathematical addition.
38+
39+
let amountSpent = 35;
40+
let amountSaved = "15";
41+
console.log ("amountSpent is a " + typeof(amountSpent));
42+
console.log ("amountSaved is a " + typeof(amountSaved));
43+
let amountBilled = amountSpent - amountSaved;
44+
console.log("amountBilled is a " + typeof(amountBilled));
45+
//Through implicit conversion, JavaScript took the amountSaved and converted its data type from a string to a number to do the mathematical subraction in the amountBilled variable.
46+
47+
let month = String(3);
48+
let day = String(14);
49+
let year = String(2025);
50+
let fullDate = month + "/" + day + "/" + year;
51+
console.log(`Pi Day is ${fullDate} and also STL Day!`);
52+
//I utilized the String() function to explicity convert the numbers for the month, day, and year to strings before inputing the data into the fullDate variable.

0 commit comments

Comments
 (0)