Skip to content

Commit ef5dd04

Browse files
committed
Answer added
1 parent ce92942 commit ef5dd04

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

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

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ Write their own code that demonstrates:
1616
Include at least one edge case, like NaN, undefined, or null .
1717
Use console.log() to clearly show the before-and-after type conversions.
1818
19-
*/
2019
2120
2221
let result = "5" - 2;
@@ -30,3 +29,41 @@ if (isValid) {
3029
let age = "25";
3130
let totalAge = age + 5;
3231
console.log("Total Age: " + totalAge);
32+
33+
*/
34+
35+
//Fixed code
36+
37+
//Part 1:
38+
//1. Explicitly convert string 5 to number 5 substracting would have forced the conversion but this conversion gives more clarity
39+
let result = Number("5") - 2; // 3
40+
console.log("The result is: " + result); //The result is: 3
41+
42+
//2. Conversion of string "false" to boolean as Boolean("false") is truthy and will return "This is valid!" but doe to this conversion the boolean will be false and execute else statement i.e "This is not valid!"
43+
let isValid = JSON.parse("false");
44+
if (isValid) {
45+
console.log("This is valid!");
46+
} else {
47+
console.log("This is not valid!"); // "This is not valid!"
48+
}
49+
50+
// 3. when it is age = "25" the output of the totalAge will be 255 which is not the expected result instead by converting the age to number the output will be correct i.e 30
51+
let age = "25";
52+
let totalAge = Number(age) + 5; // 30
53+
console.log("Total Age: " + totalAge) // Total Age: 30
54+
55+
56+
// Implicit Conversion Example:
57+
58+
let implResult = "10" * 2; // The multiplication operator "*" forces the string "10" to be converted to a number.
59+
console.log("After implicit conversion: " + implResult); // 20
60+
61+
// Explicit Conversion Example:
62+
let NumberString = "123"; // valid number string
63+
let expliNumber = Number(NumberString); // explicitly converts string to a number
64+
console.log("Explicitly converted '123' to number:", expliNumber); // 123
65+
66+
// Edge Case:
67+
let nonNumberString = "Edge Case";
68+
let invalidConversion = Number(nonNumberString);
69+
console.log("Converting 'Edge Case' results in:", invalidConversion); // NaN

0 commit comments

Comments
 (0)