22
33// Predict the output of the following code:
44// =============> Write your prediction here
5+ // All 3 console.logs will print "3" because the getLastDigit
6+ // function ignores its parameter and always returns the hardcoded
7+ // const num which is 103.
58
69const num = 103 ;
710
@@ -15,10 +18,30 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`);
1518
1619// Now run the code and compare the output to your prediction
1720// =============> write the output here
21+ // The output is:
22+ // The last digit of 42 is 3
23+ // The last digit of 105 is 3
24+ // The last digit of 806 is 3
25+
1826// Explain why the output is the way it is
1927// =============> write your explanation here
28+ // The function uses a hardcoded variable num = 103 from outside
29+ // the function instead of the num parameter that is passed to the
30+ // function. Therefore, it always returns the last digit of 103.
31+ // To fix this I can remove the const num = 103 and add num as a
32+ // parameter to the function so each call to getLastDigit will use
33+ // the number passed in as an argument (its own input) instead of the
34+ // hardcoded value.
35+
2036// Finally, correct the code to fix the problem
2137// =============> write your new code here
38+ function getLastDigit ( num ) {
39+ return num . toString ( ) . slice ( - 1 ) ;
40+ }
41+
42+ console . log ( `The last digit of 42 is ${ getLastDigit ( 42 ) } ` ) ;
43+ console . log ( `The last digit of 105 is ${ getLastDigit ( 105 ) } ` ) ;
44+ console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ;
2245
2346// This program should tell the user the last digit of each number.
2447// Explain why getLastDigit is not working properly - correct the problem
0 commit comments