Skip to content

Commit c5a94c6

Browse files
Added explicit type conversions to avoid bugs and improve clarity. Wrote logic that uses implicit and explicit conversion to determine if a person has a hat and how many.
1 parent ce92942 commit c5a94c6

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

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

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

2121

22-
let result = "5" - 2;
23-
console.log("The result is: " + result);
22+
let result = Number("5") - 2;
23+
console.log("The result is: " + result);// added Number conversion function to be more precise and add clarity
2424

25-
let isValid = Boolean("false");
25+
let isValid = Boolean(false);//Changed the string to boolean so that it would evaluate false
2626
if (isValid) {
27-
console.log("This is valid!");
27+
console.log("This is valid and true");
28+
}
29+
else {
30+
console.log("This is valid and false!");
2831
}
2932

3033
let age = "25";
31-
let totalAge = age + 5;
34+
let totalAge = Number(age) + 5; // added Number() function so that we are adding and not concatenating
3235
console.log("Total Age: " + totalAge);
36+
37+
//implicit conversion of null to false
38+
let hat = null;
39+
40+
if (hat) {
41+
console.log("Check out my hat!")
42+
}
43+
else {
44+
console.log("I have no hat, but check out my haircut!")
45+
}
46+
47+
//explicit conversion of number to boolean
48+
49+
let numberOfHats = 0;
50+
let hasAHat = Boolean(numberOfHats)
51+
if (hasAHat) {
52+
console.log("I have at least one hat")
53+
}
54+
else {
55+
console.log("I don't have a hat in the world")
56+
}

0 commit comments

Comments
 (0)