You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Sprint-2/2-mandatory-debug/2.js
+26-8Lines changed: 26 additions & 8 deletions
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,9 @@
1
1
// Predict and explain first...
2
2
3
+
3
4
// Predict the output of the following code:
4
-
// =============> Write your prediction here. It may run but give incorrect results because of const num & no parameter specified
5
+
// =============> Write your prediction here.
6
+
// //ANS: To return the last digit of num as a string.
5
7
6
8
7
9
constnum=103;
@@ -20,15 +22,31 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`);
20
22
// The last digit of 105 is 3
21
23
// The last digit of 806 is 3
22
24
// Explain why the output is the way it is
23
-
// =============> write your explanation here. num is a constant variable, it's value cannot change.
25
+
// =============> write your explanation here.
26
+
// //ANS:
27
+
// num is a constant variable, a hardcoded reference.
28
+
//The function getLastDigit is currently ignoring the arguments you pass to it(42, 105, 806) because of two main issues:
29
+
30
+
//Missing Parameter: The function definition function getLastDigit() does not have a parameter inside the parentheses.In JavaScript, if you pass an argument to a function that hasn't defined a parameter to receive it, the function simply ignores that input.
31
+
32
+
//Scope and Variable Reference: Inside the function, you are explicitly calling num.toString().Since num isn't defined inside the function, the engine looks at the Global Scope, finds const num = 103, and uses that value every single time the function runs.
33
+
24
34
// Finally, correct the code to fix the problem
25
35
// =============> write your new code here
26
-
functiongetLastDigit(){
27
-
returnnum.toString().slice(-1);
36
+
constnum=103;// This is now ignored by the function
37
+
38
+
// We add 'n' as a parameter to "catch" the numbers we pass in
39
+
functiongetLastDigit(n){
40
+
// We call toString() on 'n' instead of the global 'num'
41
+
returnn.toString().slice(-1);
28
42
}
43
+
44
+
console.log(`The last digit of 42 is ${getLastDigit(42)}`);
45
+
console.log(`The last digit of 105 is ${getLastDigit(105)}`);
46
+
console.log(`The last digit of 806 is ${getLastDigit(806)}`);
47
+
29
48
// This program should tell the user the last digit of each number.
30
49
// Explain why getLastDigit is not working properly - correct the problem
31
-
// getLastDigit is not working properly because the value for num is fixed at '103'
32
-
functiongetLastDigit(num){
33
-
returnnum.toString().slice(-1);
34
-
}
50
+
//ANS: Done above.
51
+
// ANS:getLastDigit was not working properly because the value for num is fixed at '103'
0 commit comments