11// Predict and explain first...
22
33// Predict the output of the following code:
4- // =============> Write your prediction here
4+ // =============> get rid of const num = 103 as it is defined in global scope. the output will be always 3.
55
66const num = 103 ;
77
@@ -14,11 +14,27 @@ console.log(`The last digit of 105 is ${getLastDigit(105)}`);
1414console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ;
1515
1616// Now run the code and compare the output to your prediction
17- // =============> write the output here
17+ // =============> The last digit of 42 is 3
18+ //The last digit of 105 is 3
19+ //The last digit of 806 is 3
20+ //
21+
1822// Explain why the output is the way it is
19- // =============> write your explanation here
23+ //num is always 103 inside the function (from the global variable).
24+ //So, every call to getLastDigit() returns "3" (the last digit of 103).
25+ //The arguments you pass (like 42, 105) are ignored because the function doesn't take parameters.
26+
27+
2028// Finally, correct the code to fix the problem
21- // =============> write your new code here
29+ // =============> my new code:
30+ function getLastDigit ( num ) { return num . toString ( ) . slice ( - 1 ) ; } ;
31+
32+ console . log ( `The last digit of 42 is ${ getLastDigit ( 42 ) } ` ) ;
33+ console . log ( `The last digit of 105 is ${ getLastDigit ( 105 ) } ` ) ;
34+ console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ;
2235
36+ // The output will be: The last digit of 42 is 2
37+ // The last digit of 105 is 5
38+ // The last digit of 806 is 6
2339// This program should tell the user the last digit of each number.
2440// Explain why getLastDigit is not working properly - correct the problem
0 commit comments