Blockchain 17 min read

Build a Simple JavaScript Blockchain: Theory, Code, and Proof‑of‑Work Demo

This article walks through blockchain fundamentals, explains key concepts like decentralization, immutability, and proof‑of‑work, and provides a complete JavaScript implementation with code examples, testing steps, and a practical demo that records World Cup predictions.

ELab Team
ELab Team
ELab Team
Build a Simple JavaScript Blockchain: Theory, Code, and Proof‑of‑Work Demo

Story Introduction

This tutorial begins with a humorous story about a front‑end engineer named Xiao Ming who predicts World Cup winners and decides to build a website to record his forecasts.

He designs the front‑end, enlists a teammate for a back‑end service with two APIs, and integrates them into a purely front‑end rendered site.

After correctly predicting the 2010 champion, his girlfriend doubts his claim, prompting him to create the prediction site.

Basic Concepts

What Is a Blockchain?

A blockchain is a special distributed database organized as a linked list of blocks.

Each block contains:

timestamp – block creation time

nonce – proof of work value

data – stored information

previousHash – hash of the preceding block

hash – hash of the current block calculated from the above fields

Key Characteristics

Decentralized storage – no single authority controls the data.

Immutability – altering a block changes its hash, breaking the chain; the network resolves to the longest valid chain.

Immutability is achieved through cryptographic hashing and economic incentives, commonly referred to as mining.

Practical: Build a Basic Blockchain Demo with JavaScript

Implement a Basic Block

The block class stores the previous hash, timestamp, data, a nonce, and computes its own hash.

const crypto = require('crypto');
class Block {
  constructor(previousHash, timestamp, data) {
    this.previousHash = previousHash;
    this.timestamp = timestamp;
    this.data = data;
    this.nonce = 0;
    this.hash = this.calculateHash();
  }
  // Calculate the block's hash
  calculateHash() {
    return crypto.createHash('sha256')
      .update(this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce)
      .digest('hex');
  }
}

Create the Chain

The blockchain is an array starting with a genesis block and provides methods to retrieve the latest block and add new ones.

class Blockchain {
  constructor() {
    this.chain = [this.createGenesisBlock()];
    this.difficulty = 2; // initial proof‑of‑work difficulty
  }
  createGenesisBlock() {
    return new Block(0, "20/05/2022", "Genesis block", "0");
  }
  getLatestBlock() {
    return this.chain[this.chain.length - 1];
  }
  addBlock(newBlock) {
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.mineBlock(this.difficulty);
    this.chain.push(newBlock);
  }
  isChainValid() {
    for (let i = 1; i < this.chain.length; i++) {
      const currentBlock = this.chain[i];
      const previousBlock = this.chain[i - 1];
      if (currentBlock.hash !== currentBlock.calculateHash()) return false;
      if (currentBlock.previousHash !== previousBlock.hash) return false;
    }
    return true;
  }
}

Proof‑of‑Work (POW)

POW adds computational difficulty by requiring the block hash to start with a number of leading zeros defined by the difficulty.

mineBlock(difficulty) {
  while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {
    this.nonce++;
    this.hash = this.calculateHash();
  }
}

Testing the Chain

Instantiate the blockchain, add two blocks with World Cup predictions, and verify validity before and after tampering.

let firstChain = new Blockchain();
firstChain.addBlock(new Block(0, "21/05/2022", { champion: 'Spain' }));
firstChain.addBlock(new Block(1, "22/05/2022", { champion: 'China' }));
console.log('firstChain valid? ' + firstChain.isChainValid(), firstChain.chain);
firstChain.chain[1].data = { champion: 'korea' };
console.log('firstChain valid? ' + firstChain.isChainValid(), firstChain.chain);

Conclusion

The article demonstrates how to implement a simple blockchain in JavaScript, covering core concepts, code structure, proof‑of‑work, and validation. It also discusses the benefits of decentralization and immutability, as well as drawbacks such as low throughput and high energy consumption.

blockchaindistributed ledgerProof of Workdemo
ELab Team
Written by

ELab Team

Sharing fresh technical insights

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.