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
+29-4Lines changed: 29 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -19,14 +19,39 @@ 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;// This is an example of an implicit type conversion because the string "5" is automatically converted to the number 5 since this is arithmetic involving subtraction. Since the result is correct, I did not change the code.
23
23
console.log("The result is: "+result);
24
24
25
-
letisValid=Boolean("false");
25
+
letisValid=Boolean(false);// Here I made an explicit type conversion by removing the quotation marks around the value false to prevent the Boolean function from being evaluated as true do to the string "false" being evaluated as truthy and the rest of the code from running. However, a string being automatically converted to true during evaluation is an implicit type conversion.
26
26
if(isValid){
27
27
console.log("This is valid!");
28
28
}
29
29
30
-
letage="25";
31
-
lettotalAge=age+5;
30
+
letage="25";
31
+
letnum=Number(age);// Here I am performing an explicit type conversion by converting the string of "25" to a number 25 using the Number() method.
32
+
lettotalAge=num+5;// Here I am using the variable num so the addition can be performed correctly and avoid concatenation of a string and a number.
32
33
console.log("Total Age: "+totalAge);
34
+
35
+
// My examples for Part 2:
36
+
37
+
// Example 1 is an example of explicit type conversion designed to illustrate why zero should be used to represent the absence of a value rather than undefined when calculating an average.
38
+
39
+
leta=undefined;// Here undefined is being used to represent the absence of a quantity that will be used to calculate an average.
40
+
letb=2;
41
+
42
+
letaverage=((a+b)/2);
43
+
44
+
console.log(average);// The result of the average is NaN because undefined results in the variable "a" not being assigned a value rather than representing the absence of a quantity.
45
+
46
+
letx=0;// Here I have explicitly changed the value of undefined to zero so the absence of a quantity is correctly represented, and the average will be calculated correctly.
47
+
lety=2;
48
+
49
+
letaverage1=((x+y)/2);
50
+
51
+
console.log(average1);
52
+
53
+
// Example 2 is an example of implicit type conversion.
54
+
55
+
console.log(3=="3");/* This is evaluted as true because the string "3" is automaticlly converted to the number 3 before the equality comparison is performed.
56
+
This is an implicit type conversion because one data type is converted to another automatically.
0 commit comments