Skip to content

Commit 7f4d5bf

Browse files
authored
Update 3.js
Add comments explaining slice error and fix by converting number to string.
1 parent 80eefd3 commit 7f4d5bf

File tree

1 file changed

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

1 file changed

+21
-8
lines changed

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

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
11
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
2+
3+
// We want last4Digits to store the last 4 digits of cardNumber
4+
5+
// Prediction before running:
6+
// This will cause an error because cardNumber is a number,
7+
// and numbers don't have the slice() method. slice() works only on strings or arrays.
8+
9+
// Running the code would give:
10+
// TypeError: cardNumber.slice is not a function
11+
12+
// Why?
13+
// Because slice() is not defined for numbers in JavaScript.
14+
15+
// Fix:
16+
// Convert cardNumber to a string first, so we can use slice() on it.
17+
// Then slice the last 4 characters to get the last 4 digits.
18+
19+
const last4Digits = String(cardNumber).slice(-4);
20+
21+
console.log(last4Digits); // Output: 4213
22+

0 commit comments

Comments
 (0)