Skip to content

Commit a557a6f

Browse files
committed
final push
1 parent ce92942 commit a557a6f

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

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

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

2121

22-
let result = "5" - 2;
22+
let result = "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.
2323
console.log("The result is: " + result);
2424

25-
let isValid = Boolean("false");
25+
let isValid = 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.
2626
if (isValid) {
2727
console.log("This is valid!");
2828
}
2929

30-
let age = "25";
31-
let totalAge = age + 5;
30+
let age = "25";
31+
let num = 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+
let totalAge = 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.
3233
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+
let a = undefined; // Here undefined is being used to represent the absence of a quantity that will be used to calculate an average.
40+
let b = 2;
41+
42+
let average = ((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+
let x = 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+
let y =2;
48+
49+
let average1 =((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.
57+
*/

0 commit comments

Comments
 (0)