11// Predict and explain first...
22
33// Predict the output of the following code:
4- // =============> Write your prediction here
4+ // =============> Write your prediction here: It may run but give incorrect results because of const num & no parameter specified
55
66const num = 103 ;
77
@@ -14,11 +14,33 @@ 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+ // =============> write the output here:
18+ // The last digit of 42 is 3
19+ // The last digit of 105 is 3
20+ // The last digit of 806 is 3
1821// Explain why the output is the way it is
19- // =============> write your explanation here
22+ // =============> write your explanation here;
23+ // num is a constant variable, it's value cannot change.
2024// Finally, correct the code to fix the problem
2125// =============> write your new code here
26+ let num = 103 ;
2227
28+ function getLastDigit ( ) {
29+ return num . toString ( ) . slice ( - 1 ) ;
30+ }
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 ) } ` ) ;
2335// This program should tell the user the last digit of each number.
2436// Explain why getLastDigit is not working properly - correct the problem
37+ // getLastDigit is not working properly becuase the value for num is fixed at '103'
38+ // Corrected program:
39+
40+ function getLastDigit ( num ) {
41+ return num . toString ( ) . slice ( - 1 ) ;
42+ }
43+
44+ console . log ( `The last digit of 42 is ${ getLastDigit ( 42 ) } ` ) ;
45+ console . log ( `The last digit of 105 is ${ getLastDigit ( 105 ) } ` ) ;
46+ console . log ( `The last digit of 806 is ${ getLastDigit ( 806 ) } ` ) ;
0 commit comments