Skip to content

Commit 465a4f6

Browse files
Fixed type conversion bugs and added examples
1 parent ce92942 commit 465a4f6

File tree

1 file changed

+27
-24
lines changed

1 file changed

+27
-24
lines changed
Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,35 @@
1-
/*
1+
// Part 1: Debugging Type Conversion
22

3-
Part 1: Debugging Challenge
4-
The JavaScript code below contains intentional bugs related to type conversion.
5-
Please do the following:
6-
- Run the script to observe unexpected outputs.
7-
- Debug and fix the errors using explicit type conversion methods like Number() , String() , or Boolean() where necessary.
8-
- Annotate the code with comments explaining why the fix works.
3+
// Convert "5" to a number and subtract 2
4+
let result = Number("5") - 2;
5+
console.log("The result is: " + result); // Result is 3
96

10-
Part 2: Write Your Own Examples
11-
Write their own code that demonstrates:
12-
- One example of implicit type conversion.
13-
- One example of explicit type conversion.
7+
// "false" is a non-empty string, so it's always true
8+
let isValid = Boolean("false");
9+
if (isValid) {
10+
console.log("This is valid!"); // This is valid!
11+
}
1412

15-
*We encourage you to:
16-
Include at least one edge case, like NaN, undefined, or null .
17-
Use console.log() to clearly show the before-and-after type conversions.
13+
// Convert "25" to a number before adding 5
14+
let age = "25";
15+
let totalAge = Number(age) + 5;
16+
console.log("Total Age: " + totalAge); // Total Age: 30
1817

19-
*/
2018

19+
// Part 2: Type Conversion Examples
2120

22-
let result = "5" - 2;
23-
console.log("The result is: " + result);
21+
// Implicit conversion: "5" becomes a string, so we get "5" + "10"
22+
let number = 10;
23+
let resultImplicit = "5" + number;
24+
console.log("Implicit Conversion: " + resultImplicit); // 510
2425

25-
let isValid = Boolean("false");
26-
if (isValid) {
27-
console.log("This is valid!");
28-
}
26+
// Explicit conversion: Convert "100" from string to number
27+
let strNumber = "100";
28+
let convertedNumber = Number(strNumber);
29+
console.log("Before: " + strNumber); // Before: 100
30+
console.log("After: " + convertedNumber); // After: 100
2931

30-
let age = "25";
31-
let totalAge = age + 5;
32-
console.log("Total Age: " + totalAge);
32+
// Edge case: "hello" can't be converted to a number, so we get NaN
33+
let invalidNumber = "hello";
34+
let invalidConversion = Number(invalidNumber);
35+
console.log("Edge Case (NaN): " + invalidConversion); // NaN

0 commit comments

Comments
 (0)