# How can I get next check digit using luhn algorithm in javascript

#### Tags: check-digit, javascript, luhn

I have the following code that validates if a certain digits is valid using luhn algorithm module 10.

```function isCheckdigitCorrect(value) {
// accept only digits, dashes or spaces
if (/[^0-9-s]+/.test(value)) return false;

var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/D/g, "");

for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);

if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}

nCheck += nDigit;
bEven = !bEven;
}

return (nCheck % 10) == 0;
}
```

I need another function that generates the next check-digit actually by giving four digit number so the 5th digit would be next digit checksum.

By modifying the current function to this one I was able to get next checkdigit:

```function getCheckDigit(value) {
if (/[^0-9-s]+/.test(value)) return false;

var nCheck = 0, nDigit = 0, bEven = true;
value = value.replace(/D/g, "");

for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);

if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}

nCheck += nDigit;
bEven = !bEven;
}
return (1000 - nCheck) % 10;
}
```

Source: stackoverflow