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
+21-3Lines changed: 21 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -19,14 +19,32 @@ Use console.log() to clearly show the before-and-after type conversions.
19
19
*/
20
20
21
21
22
-
letresult="5"-2;
22
+
letresult="5"-2;// The string "5" is implicitly converted to a number 5 due to the subtraction operator. If the addition operator was used, the string "5" would be concatenated to the number 2 to get the string "52".
23
23
console.log("The result is: "+result);
24
24
25
-
letisValid=Boolean("false");
25
+
letisValid=Boolean("false");// The string "false" is a truthy value, so the boolean function will return true. I am unsure if this code is supposed to have an error, or if it is supposed to run due to a true boolean value.
26
26
if(isValid){
27
27
console.log("This is valid!");
28
28
}
29
29
30
-
letage="25";
30
+
letage=Number("25");// Explicit type conversion from string to number. By doing this, the string "25" is converted to a number 25 which can now be added to 5 to get the total age.
31
31
lettotalAge=age+5;
32
32
console.log("Total Age: "+totalAge);
33
+
34
+
// Part 2: Write Your Own Examples
35
+
// Implicit Type Conversion Example
36
+
letimplicitConversion="5"+2;
37
+
console.log(implicitConversion);
38
+
39
+
// Explicit Type Conversion Example
40
+
letexplicitConversion=Number("5")+2;
41
+
console.log(explicitConversion);
42
+
43
+
//edge case example
44
+
letemptyNumber;//This variable is undefined.
45
+
console.log(emptyNumber);
46
+
emptyNumber=Boolean(emptyNumber);//This variable is now a boolean value of false.
47
+
console.log(emptyNumber);
48
+
letedgeCase=Number("5")+Number(emptyNumber);//The string "5" is converted to a number 5, and the boolean value of false is converted to a number 0.
0 commit comments