-
Notifications
You must be signed in to change notification settings - Fork 399
Expand file tree
/
Copy pathexplicit-and-implicit-conversion-in-javascript.js
More file actions
60 lines (48 loc) · 2.34 KB
/
Copy pathexplicit-and-implicit-conversion-in-javascript.js
File metadata and controls
60 lines (48 loc) · 2.34 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
59
60
/*
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.
*/
let result = "5" - 2;
console.log("The result is: " + result);
let isValid = Boolean("false");
if (isValid) {
console.log("This is valid!");
}
let age = "25";
let totalAge = age + 5;
console.log("Total Age: " + totalAge);
// Example 1: Subtraction operator triggers implicit type conversion from string to number
let result = "5" - 2; // "5" is implicitly converted to number 5 during subtraction
console.log("The result is: " + result); // Output: 3
// Example 2: Boolean conversion of a non-empty string ("false") is true
let isValid = Boolean("false"); // "false" is a non-empty string, so Boolean() returns true
if (isValid) {
console.log("This is valid!"); // This will run because isValid is true
}
// Example 3: String concatenation with + operator, no type conversion involved
let age = "25"; // age is a string
let totalAge = age + 5; // '+' concatenates strings if any operand is a string
console.log("Total Age: " + totalAge); // Output: "Total Age: 255"
// Fix for Example 2: Explicitly convert the string "false" to a Boolean value
let isValid = Boolean("false"); // This is correct technically, but to demonstrate explicit conversion:
// Better way: explicitly convert string to Boolean based on content
let isValidExplicit = String("false") === "true"; // Now, isValidExplicit is false
if (isValidExplicit) {
console.log("This is valid!");
} else {
console.log("This is NOT valid!"); // This will run because "false" !== "true"
}
// Fix for Example 3: Convert age string to number before adding
let totalAgeCorrected = Number(age) + 5; // Explicitly convert string to number
console.log("Total Age (number): " + totalAgeCorrected); // Output: 30