|
1 |
| -/* |
| 1 | +// Part 1: Debugging Type Conversion |
2 | 2 |
|
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 |
9 | 6 |
|
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 | +} |
14 | 12 |
|
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 |
18 | 17 |
|
19 |
| -*/ |
20 | 18 |
|
| 19 | +// Part 2: Type Conversion Examples |
21 | 20 |
|
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 |
24 | 25 |
|
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 |
29 | 31 |
|
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