Skip to content

Commit 9cf79b9

Browse files
committed
Code changes for implicit and explicit
1 parent ce92942 commit 9cf79b9

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

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

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

21-
22-
let result = "5" - 2;
21+
// the '-' operator makes "5" to 5 into a number, so it works as expected, but it could be clearer if we explicitly converts string to a number
22+
// Explicit type conversion to number for correct subtraction, using Number() convert "5" to 5
23+
let result = Number("5") - 2;
2324
console.log("The result is: " + result);
2425

25-
let isValid = Boolean("false");
26+
//Boolean conversion: converts non-empty string to true
27+
let isValid = Boolean("false"); // "false"(string) is truthy, So isvalid becomes true since it gives output
2628
if (isValid) {
2729
console.log("This is valid!");
2830
}
2931

32+
//explicit type conversion
3033
let age = "25";
31-
let totalAge = age + 5;
34+
// Converting age from string to number before adding
35+
let totalAge = Number(age) + 5;
3236
console.log("Total Age: " + totalAge);
37+
38+
// One example of implicit conversion
39+
40+
let number = 30;
41+
let booleanValue = true;
42+
let sumOutput = number + booleanValue; // implicit conversion booleanvalue 'True' gives value as 1 and returns output
43+
console.log("Implicit conversion output: " + sumOutput, '-', typeof(sumOutput));
44+
45+
//edge case : null implicitly converted to a number
46+
let nullValue = null;
47+
let sumWithNull = number + nullValue; // implicit conversion: Null treated as 0
48+
console.log("Implicit conversion with Null: " + sumWithNull, '-', typeof(sumWithNull) );
49+
50+
51+
// One example of explicit conversion
52+
let firstNumber = "10";
53+
let secondNumber = 10.5;
54+
let expectedOutput = firstNumber + secondNumber; // before explicit conversion returns string
55+
console.log("Explicit conversion output before type conversion: " + expectedOutput, '-', typeof(expectedOutput));
56+
let expectedOutput1 = Number(firstNumber) + secondNumber; // explicit conversion to number returns number
57+
console.log("Explicit conversion output after type conversion: " + expectedOutput1, '-', typeof(expectedOutput1));
58+
59+
// edge case : Nan explicitly converted to number
60+
let nanNumber = "Good morning";
61+
let conversionOutput = Number(nanNumber); // explicit conversion gives NaN
62+
console.log("Explicit conversion of Nan: " + conversionOutput);

0 commit comments

Comments
 (0)