22
33// Predict the output of the following code:
44// =============> Write your prediction here
5+ // I predict that all three log statements will output: "The last digit of 42 is 3", "105 is 3", "806 is 3"
6+ // Because the getLastDigit function doesn’t use the input — it always returns the last digit of the constant
7+ // `num = 103`.
58
9+ // Original Code
610const num = 103 ;
711
812function getLastDigit ( ) {
@@ -15,10 +19,25 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`);
1519
1620// Now run the code and compare the output to your prediction
1721// =============> write the output here
22+ // The actual output is:
23+ // The last digit of 42 is 3
24+ // The last digit of 105 is 3
25+ // The last digit of 806 is 3
26+
1827// Explain why the output is the way it is
1928// =============> write your explanation here
29+ // The function `getLastDigit` doesn't take any parameter, and it always uses the fixed variable `num = 103`.
30+ // So regardless of the input in the log statements, the function always returns the last digit of 103, which is "3".
31+
2032// Finally, correct the code to fix the problem
2133// =============> write your new code here
34+ function getLastDigit ( number ) {
35+ return number . toString ( ) . slice ( - 1 ) ;
36+ }
37+
38+ console . log ( `The last digit of 42 is ${ getLastDigit ( 42 ) } ` ) ; // 2
39+ console . log ( `The last digit of 105 is ${ getLastDigit ( 105 ) } ` ) ; // 5
40+ console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ; // 6
41+
42+ // Now the function works correctly by taking a number as input and returning its last digit.
2243
23- // This program should tell the user the last digit of each number.
24- // Explain why getLastDigit is not working properly - correct the problem
0 commit comments