-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexplicit-and-implicit-conversion-in-javascript.js
More file actions
58 lines (44 loc) · 2.02 KB
/
Copy pathexplicit-and-implicit-conversion-in-javascript.js
File metadata and controls
58 lines (44 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
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.
Part 2: Write Your Own Examples
Write their own code that demonstrates:
- One example of implicit type conversion.
- One example of explicit type conversion.
*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.
*/
// Implicit type conversion works here because "-" forces string to number
let result = "5" - 2;
console.log("The result is: " + result); //output:3
// Boolean conversion: non-empty strings are always true,
// but "false" as a string is still truthy, so this is a bit misleading
let isValid = Boolean("false");
if (isValid) {
console.log("This is valid!"); // Will always print
}
// Fix: Convert age to a number before adding
let age = "25";
let totalAge = age + 5; //age is a string, so (+) operator will concatenate instead of add
console.log("Total Age: " + totalAge); // 255
// Convert string to number before adding
let fixedTotalAge = Number(age) + 5;
console.log("Fixed Total Age:", fixedTotalAge); // 30
// Explanation: Number(age) converts "25" to 25, so math(+) operator works correctly
// Task 2 Implicit Type conversion Example
// Explanation: JavaScript automatically converts "10" to number
let implicitExample = "10" * 2;
console.log("Implicit Result:", implicitExample); // 20
console.log("Type:", typeof implicitExample); // number
// Explicit Type Conversion Example (edge case)
let value = null;
let convertedValue = Number(value);
console.log("Before:", value); // null
console.log("After:", convertedValue); // 0
console.log("Type:", typeof convertedValue); // number
// Explanation: null is explicitly converted to 0