Last active

Embed URL


SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Luhn validation algorithm

View luhn.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
* Luhn algorithm in JavaScript: validate credit card number supplied as string of numbers
* @author ShirtlessKirk. Copyright (c) 2012.
* @license WTFPL (
var luhnChk = (function (arr) {
return function (ccNum) {
len = ccNum.length,
bit = 1,
sum = 0,
while (len) {
val = parseInt(ccNum.charAt(--len), 10);
sum += (bit ^= 1) ? arr[val] : val;
return sum && sum % 10 === 0;
}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]));

Closure compiled version (updated Feb 11, 2015):

var luhnChk=function(a){return function(c){for(var l=c.length,b=1,s=0,v;l;)v=parseInt(c.charAt(--l),10),s+=(b^=1)?a[v]:v;return s&&0===s%10}}([0,2,4,6,8,1,3,5,7,9]);

This is awesome and apparently the most performant luhncheck in js (in chrome at least). Not sure if you have seen this:

wow! awesome! not only fast, but also beautiful code <3
thank you, dude


Woww! So far the Fastest Algorithm i've tried! :+1:

oPorks commented

Well done!

Fuckk Yeahhh!!!

Spot of code golf: After reviewing subsequent edits on jsperf, I've tweaked the code. The test case is at if you want to check.

  • decrement now happens inline rather than during the while conditional check (I prefer that placement)
  • reduction of product array contents to just the doubled number value as you've already got the undoubled value (less to initialise, less to look up)
  • the use of a closure to use the product array as a parameter was intriguing
  • return statement reversed to utilise short-circuiting better (if a zero length string is sent in then the sum is 0, cosmetic really)

A variant on the jsperf page doesn't run parseInt() if using the undoubled value. Personally, I don't like using it in some places and not others so I always run it. That's why this code isn't the fastest...

Ummm, WOW. TY!!!!

I am new, any one can tell me how can i use this code?
I want to validate cards.
and this code can validate all type of cards?

lebiru commented

+1 thanks!

alesch commented

@geniuscarpi: Use it as luhnChk("numberToValidate").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.