liveBook · Manning

Hash function

As explained in The Joy of JavaScript

The process of computing a fixed-size digest or hash value from input data using a hash function.

A hash function computes a string or digest from selected input values. The result summarizes an object's state and supports fast lookup and data-integrity checks, but a simple algorithm can produce collisions. section 2.1.2 section 4.3.2

Hashing serves several related purposes:

  • Hash transaction values into identifiers, such as a blockchain transactionId. section 2.1.2
  • Link blockchain blocks by including the previous block's cryptographically secure hash in the next block. section 1.6
  • Separate data assembly from digest computation so the hashing algorithm can be replaced without rewriting surrounding code. section 4.3.2

Hashing a transaction

A transaction object can define calculateHash by joining selected values such as sender and recipient, processing each character, and returning a numeric digest. A derived moneyTransaction inherits that method while adding funds. In a blockchain, changing one transaction property changes its hash and invalidates the subsequent chain. section 2.1.2 section 1.6

Listing 2.4 Creating hashTransaction with basic hashing calculation
const hashTransaction = Object.create(transaction);
 
hashTransaction.calculateHash = function calculateHash() {      #1
    const data = [this.sender, this.recipient].join('');        #2
    let hash = 0, i = 0;
    while (i < data.length) {
      hash = ((hash << 5) - hash + data.charCodeAt(i++)) << 0;
    }
    return hash**2;                                             #3
}
 
hashTransaction.calculateHash(); // 237572532174000400

Shows a basic JavaScript hash implementation that selects object values, iterates through their characters, and returns a digest. section 2.1.2

How The Joy of JavaScript covers it

How deep it goes
Explains input assembly, character-based computation, collisions, functional decomposition, purity, and replacement with a more secure algorithm.
Examples
Demonstrates transaction objects, a money transaction, chained blockchain blocks, and JavaScript calculateHash implementations.
What it assumes
Assumes some JavaScript background while requiring no blockchain background; introduces blockchain hashing through a deliberately small application.
What you can do after
Builds a basic JavaScript hash method, refactors it into composable functions, and swaps in a more secure Node.js crypto algorithm.
How it connects
Connects hashing with object inheritance, JSON.stringify, hash tables, dictionaries, blockchain, immutability, and proof of work.

Also explained in

Compare how 16 books explain hash function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.