Skip to content

Commit 2d1e8dd

Browse files
authored
Update 3.js
Add comments explaining slice error and fix by converting number to string
1 parent 5cf1cfd commit 2d1e8dd

File tree

1 file changed

+33
-8
lines changed
  • Sprint-1/2-mandatory-errors

1 file changed

+33
-8
lines changed

Sprint-1/2-mandatory-errors/3.js

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,34 @@
1+
// We want last4Digits to store the last 4 digits of cardNumber
2+
3+
/*
4+
Prediction before running:
5+
This will cause an error because cardNumber is a number,
6+
and numbers don't have the slice() method. slice() works only on strings or arrays.
7+
8+
*/
9+
10+
/*
11+
Running the code would give:
12+
TypeError: cardNumber.slice is not a function.
13+
14+
*/
15+
16+
/*
17+
Why?
18+
Because slice() is not defined for numbers in JavaScript.
19+
20+
*/
21+
22+
/*
23+
Fix:
24+
Convert cardNumber to a string first, so we can use slice() on it.
25+
Then slice the last 4 characters to get the last 4 digits.
26+
27+
*/
28+
129
const cardNumber = 4533787178994213;
2-
const last4Digits = cardNumber.slice(-4);
3-
4-
// The last4Digits variable should store the last 4 digits of cardNumber
5-
// However, the code isn't working
6-
// Before running the code, make and explain a prediction about why the code won't work
7-
// Then run the code and see what error it gives.
8-
// Consider: Why does it give this error? Is this what I predicted? If not, what's different?
9-
// Then try updating the expression last4Digits is assigned to, in order to get the correct value
30+
31+
const last4Digits = String(cardNumber).slice(-4);
32+
33+
console.log(last4Digits); // Output: 4213
34+

0 commit comments

Comments
 (0)