diff --git a/explicit-and-implicit-conversion-in-javascript.js b/explicit-and-implicit-conversion-in-javascript.js index ede0ccd..a5ebab5 100644 --- a/explicit-and-implicit-conversion-in-javascript.js +++ b/explicit-and-implicit-conversion-in-javascript.js @@ -1,32 +1,35 @@ -/* +// Part 1: Debugging Type Conversion -Part 1: Debugging Challenge -The JavaScript code below contains intentional bugs related to type conversion. -Please do the following: - - Run the script to observe unexpected outputs. - - Debug and fix the errors using explicit type conversion methods like Number() , String() , or Boolean() where necessary. - - Annotate the code with comments explaining why the fix works. +// Convert "5" to a number and subtract 2 +let result = Number("5") - 2; +console.log("The result is: " + result); // Result is 3 -Part 2: Write Your Own Examples -Write their own code that demonstrates: - - One example of implicit type conversion. - - One example of explicit type conversion. +// "false" is a non-empty string, so it's always true +let isValid = Boolean("false"); +if (isValid) { + console.log("This is valid!"); // This is valid! +} - *We encourage you to: -Include at least one edge case, like NaN, undefined, or null . -Use console.log() to clearly show the before-and-after type conversions. +// Convert "25" to a number before adding 5 +let age = "25"; +let totalAge = Number(age) + 5; +console.log("Total Age: " + totalAge); // Total Age: 30 -*/ +// Part 2: Type Conversion Examples -let result = "5" - 2; -console.log("The result is: " + result); +// Implicit conversion: "5" becomes a string, so we get "5" + "10" +let number = 10; +let resultImplicit = "5" + number; +console.log("Implicit Conversion: " + resultImplicit); // 510 -let isValid = Boolean("false"); -if (isValid) { - console.log("This is valid!"); -} +// Explicit conversion: Convert "100" from string to number +let strNumber = "100"; +let convertedNumber = Number(strNumber); +console.log("Before: " + strNumber); // Before: 100 +console.log("After: " + convertedNumber); // After: 100 -let age = "25"; -let totalAge = age + 5; -console.log("Total Age: " + totalAge); +// Edge case: "hello" can't be converted to a number, so we get NaN +let invalidNumber = "hello"; +let invalidConversion = Number(invalidNumber); +console.log("Edge Case (NaN): " + invalidConversion); // NaN