Skip to content

Commit 47638c6

Browse files
committed
a commit
1 parent ce92942 commit 47638c6

File tree

1 file changed

+43
-4
lines changed

1 file changed

+43
-4
lines changed

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

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,54 @@ Use console.log() to clearly show the before-and-after type conversions.
1818
1919
*/
2020

21-
22-
let result = "5" - 2;
21+
// broke down the variable subtraction into more steps, making the code
22+
// easier to follow. can convert x value with Number(), though the interpreter
23+
// makes the decision to convert data type automatically to a number
24+
let x = "5";
25+
let y = 2;
26+
let result = x - y;
2327
console.log("The result is: " + result);
2428

25-
let isValid = Boolean("false");
29+
// Boolean() wrapper was unnecessary and caused confusion, because it wrapped a non-empty string
30+
// which evaluated the code to boolean true. so I just initialized the false value as a bool
31+
let isValid = false;
2632
if (isValid) {
2733
console.log("This is valid!");
2834
}
2935

36+
// converting age to a primitive Number makes the addition work fine
3037
let age = "25";
31-
let totalAge = age + 5;
38+
let totalAge = Number(age) + 5;
3239
console.log("Total Age: " + totalAge);
40+
41+
42+
// MY EXAMPLES
43+
44+
// EXPLICIT CONVERSION
45+
let someInput = '5';
46+
let anotherInput = null;
47+
48+
let sumInputs;
49+
50+
if (someInput === null && anotherInput == null) {
51+
sumInputs = 0;
52+
} else if (someInput === null) {
53+
sumInputs = Number(anotherInput);
54+
} else if (anotherInput === null) {
55+
sumInputs = Number(someInput);
56+
} else {
57+
sumInputs = Number(someInput) + Number(anotherInput);
58+
}
59+
60+
console.log(sumInputs);
61+
62+
63+
// IMPLICIT CONVERSION
64+
65+
let numX = 3;
66+
let numY = '8';
67+
let product = numX * numY;
68+
69+
console.log(product);
70+
71+

0 commit comments

Comments
 (0)