const generateHash = (string) => {
  let hash = 0;
  for (const char of string) {
    hash = (hash << 5) - hash + char.charCodeAt(0);
    hash |= 0; // Constrain to 32bit integer
  }
  return hash;
};

console.log(generateHash('revenue'))

Answer from esmiralha on Stack Overflow
Top answer
1 of 16
1086

const generateHash = (string) => {
  let hash = 0;
  for (const char of string) {
    hash = (hash << 5) - hash + char.charCodeAt(0);
    hash |= 0; // Constrain to 32bit integer
  }
  return hash;
};

console.log(generateHash('revenue'))

2 of 16
475

Many of the answers here are the same String.hashCode hash function taken from Java. It dates back to 1981 from Gosling Emacs, is extremely weak, and makes zero sense performance-wise in modern JavaScript. In fact, implementations could be significantly faster by using ES6 Math.imul, but no one took notice. We can do much better than this, at essentially identical performance.

Here's one I did—cyrb53, a simple but high quality 53-bit hash. It's quite fast, provides very good* hash distribution, and because it outputs 53 bits, has significantly lower collision rates compared to any 32-bit hash. Also, you can ignore SA's CC license as it's public domain on my GitHub.

const cyrb53 = (str, seed = 0) => {
    let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
    for(let i = 0, ch; i < str.length; i++) {
        ch = str.charCodeAt(i);
        h1 = Math.imul(h1 ^ ch, 2654435761);
        h2 = Math.imul(h2 ^ ch, 1597334677);
    }
    h1  = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
    h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
    h2  = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
    h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
  
    return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};

console.log(`cyrb53('a') -> ${cyrb53('a')}`)
console.log(`cyrb53('b') -> ${cyrb53('b')}`)
console.log(`cyrb53('revenge') -> ${cyrb53('revenge')}`)
console.log(`cyrb53('revenue') -> ${cyrb53('revenue')}`)
console.log(`cyrb53('revenue', 1) -> ${cyrb53('revenue', 1)}`)
console.log(`cyrb53('revenue', 2) -> ${cyrb53('revenue', 2)}`)
console.log(`cyrb53('revenue', 3) -> ${cyrb53('revenue', 3)}`)

*It is roughly similar to the well-known MurmurHash/xxHash algorithms. It uses a combination of multiplication and Xorshift to generate the hash, but not as thorough. As a result it's significantly simpler to implement, but may not pass all tests in SMHasher. This is not a cryptographic hash function, so don't use this for security purposes.

Like any proper hash, it has a fairly acceptable "avalanche" effect, which basically means small changes in the input have big changes in the output, making the resulting hash appear more 'random':

"501c2ba782c97901" = cyrb53("a")
"459eda5bc254d2bf" = cyrb53("b")
"fbce64cc3b748385" = cyrb53("revenge")
"fb1d85148d13f93a" = cyrb53("revenue")

You can optionally supply a seed (unsigned integer, 32-bit max) for alternate streams of the same input:

"76fee5e6598ccd5c" = cyrb53("revenue", 1)
"1f672e2831253862" = cyrb53("revenue", 2)
"2b10de31708e6ab7" = cyrb53("revenue", 3)

Technically, it is a 64-bit hash, that is, two uncorrelated 32-bit hashes computed in parallel, but JavaScript is limited to 53-bit integers. If convenient, the full 64-bit output can be used by altering the return statement with a hex string or array.

return [h2>>>0, h1>>>0];
// or
return (h2>>>0).toString(16).padStart(8,0)+(h1>>>0).toString(16).padStart(8,0);
// or 
return 4294967296n * BigInt(h2) + BigInt(h1);

Be aware that constructing hex strings drastically slows down batch processing. The array is much more efficient, but obviously requires two checks instead of one. I also included BigInt, which should be slightly faster than String, but still much slower than Array or Number.


Just for fun, here's TinySimpleHash, the smallest hash I could come up with that's still decent. It's a 32-bit hash in 89 chars with better quality randomness than even FNV or DJB2:

TSH=s=>{for(var i=0,h=9;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),9**9);return h^h>>>9}
🌐
GitHub
gist.github.com › hyamamoto › fd435505d29ebfa3d9716fd2be8d42f0
JavaScript Implementation of String.hashCode() . · GitHub
console.log( String('[').hashCode(), String('a').hashCode(), String(']').hashCode(), String('[a]').hashCode(), String('[a]').hashCode() ) // Output: // 91 97 93 90551 90551 ... /** * Returns a UUIDv4 as string * * @returns {string} */ generateUuid = () => { return ( String('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx') ).replace(/[xy]/g, (character) => { const random = (Math.random() * 16) | 0; const value = character === "x" ?
🌐
A Security Site
asecuritysite.com › javascript › js04
JavaScript Hash Generator
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/js-sha3/0.9.3/sha3.min.js"></script> <script type="text/javascript" src="https://nf404.github.io/crypto-api/crypto-api.min.js"></script> <script> function hashit(message,str) { var hasher = CryptoApi.getHasher(str); hasher.update(message); document.getElementById('hash').value = "Hex: "+CryptoApi.encoder.toHex(hasher.finalize())+"\n"; document.getElementById('hash').value += "Base64: " + CryptoApi.encoder.toBase64(hasher.finalize()); } </script> <div class="indented"> <table width="100%"> <tr> <th width="15%">Input</th>
🌐
Pmav
pmav.eu › stuff › javascript-hash-code
Javascript HashCode Function
HashCode.value(new Object(arg)) === HashCode.value(new Object(arg)) // is True // but... function MyClass(value) { this.value = value; } c1 = new MyClass(99); c2 = new MyClass(99); HashCode.value(c1) === HashCode.value(c2); // is True c1 === c2; // is False ... x143 and 99 return the same code.
🌐
GitHub
github.com › HoKangInfo › js-hash-code
GitHub - HoKangInfo/js-hash-code: generate a javascript object hash coe.
algo (String|Function): The hash algorithms. default like JAVA hashCode. set (Boolean): ignore collection is object or array, has same elements, hash code is same, if true. Returns (string): Returns the javascript object hash code.
Author   HoKangInfo
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-create-hash-from-string-in-javascript
How to Create Hash From String in JavaScript? - GeeksforGeeks
July 12, 2025 - The crypto.subtle API is built into modern browsers and provides a way to perform cryptographic operations like hashing. Here is how you can generate a SHA-256 hash in the browser using crypto.subtle
🌐
QuickRef.ME
quickref.me › home › how to generate a hash of a string in javascript - quickref.me
How to generate a hash of a string in JavaScript - QuickRef.ME
In this Article we will go through how to generate a hash of a string only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.
Find elsewhere
🌐
npm
npmjs.com › package › object-hash
object-hash - npm
<script src="object_hash.js" type="text/javascript"></script> <script> var hash = objectHash.sha1({foo:'bar'}); console.log(hash); // e003c89cdf35cdf46d8239b4692436364b7259f9 </script>
      » npm install object-hash
    
Published   Feb 18, 2022
Version   3.0.0
Author   Scott Puleo
🌐
npm
npmjs.com › package › js-hash-code
js-hash-code - npm
generate a javascript object hash coe.. Latest version: 1.0.0, last published: 8 years ago. Start using js-hash-code in your project by running `npm i js-hash-code`. There are 3 other projects in the npm registry using js-hash-code.
      » npm install js-hash-code
    
Published   Aug 25, 2017
Version   1.0.0
Author   Robin JH Kang
🌐
npm
npmjs.com › search
hashCode - npm search
Generate and/or verify the hashcode for sys_update_xml payloads in vanilla javascript.
🌐
TutorialsPoint
tutorialspoint.com › how-to-create-a-hash-from-a-string-in-javascript
How to create a hash from a string in JavaScript?
After that, we used the reduce() method and passed the callback function as the first parameter and 0 as a second parameter representing the initial value of the hash variable. In the callback function, we generate the hash using every character's ASCII value.
🌐
GitHub
gist.github.com › remarkablemark › fd0837438d136e18c8e8eac559cd004a
A JavaScript hash generator. · GitHub
A JavaScript hash generator. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
github.com › mariazevedo88 › hash-generator-js
GitHub - mariazevedo88/hash-generator-js: A Vue.js application with a javascript implementation of String's class hashCode method in Java
A Vue.js application with a javascript implementation of String's class hashCode method in Java - mariazevedo88/hash-generator-js
Starred by 3 users
Forked by 4 users
Languages   JavaScript 88.1% | Vue 10.6% | HTML 1.3%
🌐
The Daily Signal
lowrey.me › implementing-javas-string-hashcode-in-javascript
Implementing Java's String.hashCode in JavaScript
April 23, 2018 - Something like MD5 or SHA would be overkill. I didn't need it to be secure, just unique. In Java, each string has the method hashCode() on the object. It returns a 32 bit integer that is relatively guaranteed to be unique for any given string. JavaScript has no similar comparable utility.
🌐
Chrome Web Store
chromewebstore.google.com › detail › secure-hash-generator › eaoopiddkidbkpimlfkkmkkddjbpemop
Secure Hash Generator - Chrome Web Store
The first 4 methods are from the native HTML5 SubtleCrypto (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest) API and the rest are from CryptoJS (https://github.com/brix/crypto-js) open-source JavaScript API. Please click on the - Generate - button to make hash code for the input file(s).