You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: explicit-and-implicit-conversion-in-javascript.js
+38-1Lines changed: 38 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -16,7 +16,6 @@ Write their own code that demonstrates:
16
16
Include at least one edge case, like NaN, undefined, or null .
17
17
Use console.log() to clearly show the before-and-after type conversions.
18
18
19
-
*/
20
19
21
20
22
21
let result = "5" - 2;
@@ -30,3 +29,41 @@ if (isValid) {
30
29
let age = "25";
31
30
let totalAge = age + 5;
32
31
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
+
letresult=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
+
letisValid=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
+
letage="25";
52
+
lettotalAge=Number(age)+5;// 30
53
+
console.log("Total Age: "+totalAge)// Total Age: 30
54
+
55
+
56
+
// Implicit Conversion Example:
57
+
58
+
letimplResult="10"*2;// The multiplication operator "*" forces the string "10" to be converted to a number.
0 commit comments