33// Predict the output of the following code:
44// =============> Write your prediction here
55
6+ // Prediction:
7+ // The function will always return "3".
8+ // Even though we pass 42, 105, and 806 into the function,
9+ // it will ignore those values and use the global variable `num = 103`.
10+ // Therefore, every line will print 3 as the last digit.
11+
612const num = 103 ;
713
814function getLastDigit ( ) {
@@ -13,12 +19,43 @@ console.log(`The last digit of 42 is ${getLastDigit(42)}`);
1319console . log ( `The last digit of 105 is ${ getLastDigit ( 105 ) } ` ) ;
1420console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ;
1521
22+
1623// Now run the code and compare the output to your prediction
1724// =============> write the output here
25+
26+ // Output:
27+ // The last digit of 42 is 3
28+ // The last digit of 105 is 3
29+ // The last digit of 806 is 3
30+
31+
1832// Explain why the output is the way it is
1933// =============> write your explanation here
34+
35+ // Explanation:
36+ // The function getLastDigit does not accept a parameter.
37+ // Because of that, it ignores the values passed inside the parentheses.
38+ // Instead, it always uses the global constant `num`, which is 103.
39+ // The function converts 103 to a string and takes the last character,
40+ // which is "3". That is why every output is 3.
41+
42+
2043// Finally, correct the code to fix the problem
2144// =============> write your new code here
2245
46+ function getLastDigit ( number ) {
47+ return number . toString ( ) . slice ( - 1 ) ;
48+ }
49+
50+ console . log ( `The last digit of 42 is ${ getLastDigit ( 42 ) } ` ) ; //2
51+ console . log ( `The last digit of 105 is ${ getLastDigit ( 105 ) } ` ) ; //5
52+ console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ; //6
53+
54+
2355// This program should tell the user the last digit of each number.
2456// Explain why getLastDigit is not working properly - correct the problem
57+
58+ // The function was not working properly because it did not use a parameter.
59+ // It was hard-coded to use the global variable `num` instead of the value
60+ // passed into the function. By adding a parameter (number),
61+ // the function now works correctly for any input.
0 commit comments