File tree Expand file tree Collapse file tree 1 file changed +27
-2
lines changed
Sprint-1/2-mandatory-errors Expand file tree Collapse file tree 1 file changed +27
-2
lines changed Original file line number Diff line number Diff line change 1- const cardNumber = 4533787178994213 ;
2- const last4Digits = cardNumber . slice ( - 4 ) ;
1+ // const cardNumber = 4533787178994213;
2+ // const last4Digits = cardNumber.slice(-4);
33
44// The last4Digits variable should store the last 4 digits of cardNumber
55// However, the code isn't working
66// Before running the code, make and explain a prediction about why the code won't work
77// Then run the code and see what error it gives.
88// Consider: Why does it give this error? Is this what I predicted? If not, what's different?
99// Then try updating the expression last4Digits is assigned to, in order to get the correct value
10+
11+ /**
12+ *Prediction: Why won’t this code work?
13+ const cardNumber = 4533787178994213;
14+ const last4Digits = cardNumber.slice(-4);
15+
16+
17+ The issue is that .slice() is a string method, but cardNumber here is a number — not a string.
18+ So when the code runs, JavaScript will say something like:
19+
20+ TypeError: cardNumber.slice is not a function
21+
22+ That’s because .slice() only works on strings or arrays — and numbers don’t have that method.
23+
24+ Fixing the problem
25+
26+ To use .slice(), we need to convert the number into a string first:
27+
28+ Now it works!
29+ */
30+
31+ const cardNumber = 4533787178994213 ;
32+ const last4Digits = cardNumber . toString ( ) . slice ( - 4 ) ;
33+ console . log ( last4Digits ) ; // "4213"
34+
You can’t perform that action at this time.
0 commit comments