|
1 | 1 | const cardNumber = 4533787178994213; |
2 | | -const last4Digits = cardNumber.slice(-4); |
| 2 | +const last4Digits = cardNumber.toString().slice(-4); |
| 3 | +console.log(last4Digits); |
3 | 4 |
|
4 | 5 | // The last4Digits variable should store the last 4 digits of cardNumber |
5 | 6 | // However, the code isn't working |
6 | 7 | // Before running the code, make and explain a prediction about why the code won't work |
7 | 8 | // Then run the code and see what error it gives. |
8 | 9 | // Consider: Why does it give this error? Is this what I predicted? If not, what's different? |
9 | 10 | // Then try updating the expression last4Digits is assigned to, in order to get the correct value |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +// Prediction: I believe slice counts forward from the start when you use positive values, and |
| 15 | +// backwards from the end when you use negative. So if you only put in one negative number, it's counts |
| 16 | +// backward from the end to the last 4, but can't "turn around" to count up to the end again..? |
| 17 | + |
| 18 | +// After running the code: The actual error was a TypeError, saying that cardNumber.slice is not a function. |
| 19 | +// That means you can't put anything in parenthesis after cardNumber.slice. However, when I used slice before |
| 20 | +// slice definitely takes parameters. This made me think about the fact that cardNumber is actually a |
| 21 | +// number, and slice is probably only for strings or arrays. You can't really count positions in a number. |
| 22 | + |
| 23 | +// I solved it by chaining a toString before slicing. My initial theory was completely wrong, putting a |
| 24 | +// negative number in slice is completely fine. Now last4Digits is a string, not a number. But it seems |
| 25 | +// easier to work with as a string, if specific digits need to be accessed, so I will keep it as a string. |
0 commit comments