22
33// Predict the output of the following code:
44// =============> Write your prediction here
5+ // The output will be 3 for every function call.
6+ // This is because the function does not have a parameter, so it ignores the values passed in the function calls.
7+ // Instead, it uses the global variable num, which is set to 103.
8+ // The last digit of 103 is 3, so the function always returns 3.
9+ // variable num inside function take the input from the global variable num in the outside of the function
510
611const num = 103 ;
712
@@ -15,10 +20,42 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`);
1520
1621// Now run the code and compare the output to your prediction
1722// =============> write the output here
23+ // The last digit of 42 is 3
24+ // The last digit of 105 is 3
25+ // The last digit of 806 is 3
1826// Explain why the output is the way it is
1927// =============> write your explanation here
28+ // The function getLastDigit does not have a parameter.
29+ // Even though values like 42, 105, and 806 are passed when calling the function, they are ignored.
30+
31+ // Inside the function, the variable num refers to the global variable num, which is set to 103.
32+
33+ // Each time the function runs, it converts 103 to a string and extracts the last character using slice(-1).
34+
35+ // The last digit of 103 is "3".
36+
37+ // Therefore, every function call returns "3".
2038// Finally, correct the code to fix the problem
2139// =============> write your new code here
2240
41+ function getLastDigit ( num ) {
42+ return num . toString ( ) . slice ( - 1 ) ;
43+ }
44+
45+ console . log ( `The last digit of 42 is ${ getLastDigit ( 42 ) } ` ) ;
46+ console . log ( `The last digit of 105 is ${ getLastDigit ( 105 ) } ` ) ;
47+ console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ;
48+
2349// This program should tell the user the last digit of each number.
2450// Explain why getLastDigit is not working properly - correct the problem
51+ // In the previous version, the function was not working properly because it used a global variable instead of a parameter.
52+ // Since the function did not define a parameter, it ignored the values passed during the function calls and always used the same global value.
53+
54+ // In the corrected version, the global variable was removed and a parameter num was added to the function definition.
55+ // Now, the function receives the argument passed during each function call and correctly returns the last digit of that number.
56+
57+ // Therefore, the output becomes:
58+
59+ // The last digit of 42 is 2
60+ // The last digit of 105 is 5
61+ // The last digit of 806 is 6
0 commit comments